Reputation: 51
why I am not able to get map() method index inside of Click handler function in reactjs even i have passed index from map metho, it always returning undefined. below is my implementation url
https://codesandbox.io/s/mystifying-wu-vou3c?file=/src/App.js
Upvotes: 0
Views: 143
Reputation: 3003
The arrow function toggle take 2 parameters: element and index, you're passing just index as the first parameter (that should have been element, instead), so index is undefined.
Just change your code as follow:
onClick={index => toggle(element, index)}
UPDATE
The code suggested is wrong as for a copy paste.
The event handler took a parameter that is the event object, you named that parameter index, so when you pass to toggle, it use the event instead of the map index.
Anyway, toggle needs 2 parameters, so you have to pass 2.
I think the proper solution will be:
onClick={ev => toggle(ev.target, index)}
That is fine for the toggle function, but your code still has a bug, so have a look at the @adel answer.
Upvotes: 3