I am rendering list items using an object that has nested arrays like so:
const data = {
people: [
{name: 'Person One', addresses: ['address 1', 'address 2']}
{name: 'Person Two', addresses: ['address 3', 'address 4']}
...
]
}
For some reason, when rendering the nested array addresses
and passing the index, ‘peopleIndex’ from the map
function by looping people
array, to nested component, all the peopleIndexes
is showing as 0
const [pIndex, setPeopleIndex] = useState(0)
const handleClick = (peopleIndex) => {
console.log(peopleIndex) //This is being all passed in as `0` by <ListItemComponent />
}
{
data.people.map((element, peopleIndex) => (
<div key={peopleIndex}>
<AccordianHeaderComponent onClick={() => setPeopleIndex(peopleIndex)} />
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={category?.questions}
strategy={verticalListSortingStrategy}
>
{
element.addresses.map((address, addressIndex) => (
<ListItemComponent
key={addressIndex}
handleClick={handleClick}
peopleIndex={peopleIndex}
/>
))
}
</SortableContext>
</DndContext>
</div>
))
}
// ListItemComponent
const ListItemComponent = ({handleClick, peopleIndex}) => {
const {
attributes,
isDragging,
listeners,
setNodeRef,
transform,
transition,
} = useSortable({ id: dragID });
console.log(peopleIndex) //This is all logging as 0, but should be every index in the map when looping `data.people` for each list item in iteration
return (<li
onClick{() => handleClick(peopleIndex)}
id={dragID}
ref={setNodeRef}
style={style}
{...attributes}
{...listeners}
>
...
</li>
)
}