Skip to content
Advertisement

How can I setState of specific Switch created dynamically by a map?

I have Switches created dynamically by a map like this: https://i.imgur.com/KuwY5Bb.png

By this code:

JavaScript

And it’s works but when I click one Switcher all switchers change together. This is happening because all Switches are created with the same “reference” enabled. How I set an individual var to each Switcher without Hardcoding individuals [enabled, setEnabled] to each one (I have more than 450 lines using this Switch) and How can I call a function when onChange is called without messing with this setEnabled function?

Advertisement

Answer

You need to create an object in your state instead of a boolean. and use id/index as a key of each item in object. try like this in below example I am using index as key.

JavaScript

A working code sandbox example you can fine here

https://codesandbox.io/s/magical-grass-yx1qsg?file=/src/App.js

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement