Roy
Roy

Reputation: 51

why i am not able to get map() method index inside of Click handler function in reactjs

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

Answers (2)

Mario Santini
Mario Santini

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

adel
adel

Reputation: 3507

the onClick should be like this: onClick={() => toggle(index)} so the index is from array.map and i also edited your code and remove isOpen state. here full code: code

Upvotes: 1

Related Questions