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:

const [enabled, setEnabled] = useState(false)

return(
...
{people.map((person) => (
             ...
             <Switch
                    checked={enabled}
                    onChange={setEnabled}
                    className={classNames(
                        enabled  ? 'bg-indigo-600' : 'bg-gray-200',
                        'relative inline-flex flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'
                    )}
           ...
           </Switch>
...
))

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.

const [enabled, setEnabled] = useState({})

const onEnable = (index, value) => {
  let _enabled = {...enabled};
  _enabled[index] = value
  setEnabled(_enabled)
}

return (

    {
      people.map((person, index) => ( 
              <Switch 
                 checked = {!!enabled[index]}
                 onChange = {(e)=> onEnable(index, e.target.checked)} 
                  // instead of index I recommend using id or any unique key present in your person array 
              </Switch>
            ))
    }

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