I am trying to change the value of isChecked in state when checkbox is checked.
Here's my state:
const [talles, setTalles] = useState([
{ name: 'S', isChecked: false },
{ name: 'M', isChecked: false },
{ name: 'L', isChecked: false },
{ name: 'XL', isChecked: false },
])
For each element in this state an <input type="checkbox" /> is created.
The thing is I want to dynamically change the isChecked property.
Normally I would do:
setProduct({
...product,
[e.target.name]: e.target.checked
})
But that would only work if my state was like useState({ productCheckbox: '' })
I would appreciate your help. Thanks in advance!
You can map the previous state and change the value of the changing talle:
setTalles(previousState => previousState.map(talle => {
if (talle.name === e.target.name) return ({
...talle,
isChecked: e.target.checked,
})
return talle
}))
Or same but shorter:
setTalles(previousState => previousState.map(talle =>
talle.name === e.target.name ?
({
...talle,
isChecked: e.target.checked,
})
:
talle
}))