1

I am trying to render this reactstrap CustomInput in a loop. Everything renders correctly, however, the console.log(index) always prints out 0. I'm not sure why?

Could someone please explain why this is happening and how I can fix it? I

 {managementTabData.map((item, index) => (
    <tr>
        <td>
            <CustomInput
                type="switch"
                id="exampleCustomSwitch"
                name="customSwitch"
                checked={item.allowView}
                onClick={() => console.log(index)}
            />
        </td>
    </tr>
))}
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
Just_Ice
  • 523
  • 1
  • 6
  • 12
  • Does this answer your question? [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Andy Ray Jan 28 '21 at 05:34
  • Well, I'm unable to reproduce this for similar arrangement of components. [ref](https://codesandbox.io/s/reverent-sinoussi-1x3ph?file=/src/App.js) – brc-dd Jan 28 '21 at 05:42
  • add a key to the looping item. – sharun k k Jan 28 '21 at 07:21
  • I looked into closures. But how would I rewrite this piece of code so that console.log(index) is already the correct value? – Just_Ice Jan 28 '21 at 10:35

1 Answers1

1

Issue is due to how closures work in javascript, if you add the index as id of your component and read it by event.target.id then it should work.

{managementTabData.map((item, index) => (
    <tr>
        <td>
            <CustomInput
                type="switch"
                id={index}
                name="customSwitch"
                checked={item.allowView}
                onClick={(event) => console.log(event.target.id)}
            />
        </td>
    </tr>
))}

Another option is to write function and bind to this element which is not great idea.

Pavan
  • 819
  • 6
  • 18