I have this object of objects:
[
0: {
id: 0,
name: 'Bob',
children: [
0: { id: 0, parent: 'Bob', 'name': 'Susan'},
1: { id: 1, parent: 'Bob', 'name': 'David'},
]
},
1: {
id: 1,
name: 'Christine',
children: [
0: { id: 0, parent: 'Christine', 'name': 'Iker'},
1: { id: 1, parent: 'Christine', 'name': 'Ray'},
2: { id: 2, parent: 'Christine', 'name': 'Milo'},
]
},
]
I have a list that renders all the children and I have an onClick on them. How can I get index of the parent's object when I click on the individual children itself? What I have below only returns the index of the child itself.
<div onClick={() => handleAddChild(id, index)}>
<p>{child.name}</p>
</div>
Basically when I click on a child, I want to grab the index of that child's parent object in order to update the children list for that particular parent using setState(). So if I click Iker, I should get the index 1 back of Christine's object then update state using this method (but mine is dynamic): https://stackoverflow.com/a/49502115/10211209. If there another way to do this by matching the parent name property?
Thank you!
If you are looping through and rendering the parents first and then the children. You could just pass through the parent index as an additional parameter. e.g
return this.parents.map((item, parentIndex) => (
<span className="parent" key={index}>
{item.children.map((child, index) => {
<div onClick={() => handleAddChild(child.id, index, parentIndex)}>
<p>{child.name}</p>
</div>
})}
</span>
));