I'm trying to put all checked checkboxes in the state array. I am able to add values to the array, but I cannot delete the value when I uncheck the box. I've tried using splice and delete by index, also tried deleting through a filter. It works, but it works slowly and incorrectly. For example I can uncheck all the checkboxes and one value stay in the state. Please check what I'm doing wrong Here is a Sandbox link and my code below
const [state, setState] = useState({
address: [],
})
const checkboxChange = (e) => {
const { name, checked } = e.target
if (checked === true) {
setState((prevState) => ({
...prevState,
address: [...prevState.address, name],
}))
}
if (checked === false) {
setState((prevState) => ({
...prevState,
address: [...prevState.address].filter((it) => it.id !== it.id),
}))
}
}
{list.map((it, index) => (
<div key={it.id}>
<label>
<input
className="mr-2"
checked={state.address.index}
key={it.id}
name={it.id}
defaultValue="false"
onChange={checkboxChange}
type="checkbox"
/>
{it.name}
</label>
</div>
))}
it.id !== it.idwill always evaluate false`. Why are you storing checked state in an array?spliceon a react state because it mutates the array.