I have 2 components. The parent is a mapped list. In each map render, there is a dropdown menu. The dropdown menu component has a handler prop that you pass a function to and it sends you back the data of the clicked item. See the simplified code below.
const ParantList = () => {
const listData = [1,2,3]
const handleClick = (x, i) => {
// Here x will return data from the child
// i returns nothing but I would like it to be the current index of listData
return [x, i]
}
return (
<div>
{listData.map((x, i) => <Child handleClick={handleClick} /> )}
</div>
)
}
const Child = ({handleClick}) => {
const differentList = [4,5,6]
return (
<Dropdown>
{differentList.map(x =>
<Dropdown.Item onClick={()=>handleClick(x)}>
{x}
</Dropdown.Item>
)}
</Dropdown>)
}
The issue is in the handle click function in the parent, I need the data from the differentList in the child to pass to the function, which works fine. However, I also need the index or data from the corresponding item (listData) in which the drop-down was clicked in the parent map. So the handleClick function needs the data from both lists.
The simple solution is to pass down the current index of the listData list to the child. HOWEVER, in reality, the child component is a package that I can't (or don't know how to) change the function handler. Is there a simple way to pass a function to a child but pass a prop at the same time? Thank you!
CodePudding user response:
Just pass listData's index to handleClick
.
{listData.map((x, i) => <Child handleClick={(childX) => handleClick(childX, i)} /> )}