0

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

2
  • The call to toggle(index) is wrong, the second parameter of toggle() method is holding index. So you need to call like toggle('', index) Commented Aug 1, 2020 at 7:17
  • Yes I have made the sane changes but nothing changed, you can check the updated code on same given url. Commented Aug 1, 2020 at 7:36

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

As per my knowledge map function takes more than 2 parameters instead of Arrow, I m just receiving index from map to my arrow function, but I have made your suggested changes but nothing happened, still just returning undefined
Sorry, I notice now, you named the onClick arrow function first parameter index, that is the issue. I saw now @adel answered highlight that. Anyway, by adding the element as I suggested, on your code example, is not printing undefined anymore.
1

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

4 Comments

Yes Thanks, Adel for your Valuable Time its working fine now, but can you please suggest what is current & where from you are getting it in settabToggle function? as you are not using tabToggle state for changing its value
setState hooks has a callback which can access current state so current is the current tabToggle state.
okay Thaks, but why you have define condition like this settabToggle(current => (current === index ? undefined : index)); instead settabToggle(current => (current === index ? index: undefined)); as we have to toggle based on matching index.
yes if the current tab is Opened and clicked again we want to close it so the condition should be current === index?undefined:index

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.