Why does clicking a checkbox cancel the previous selection in React?
P粉729198207
P粉729198207 2023-08-13 10:57:24
0
1
658
<p>I have multiple checkboxes and when I click on one checkbox and then the next, the previous checkbox gets deselected, do you know why? </p> <p>This is my checkbox component: </p> <pre class="brush:php;toolbar:false;">const Checkbox = ({ key, id, label, checked, name, onChange }:any) => { return ( <div className="checkbox-wrapper"> <input multiple key={id} id={id} type="checkbox" checked={checked} name={name} onChange={onChange} /> <label htmlFor={id}>{label}</label> </div> ) }</pre> <p>This is what the main component looks like, the data is in an array and then mapped out, but I'm not sure why it deselects the previous checkbox, I've removed a lot of other useless JSX code:< /p> <pre class="brush:php;toolbar:false;">const checkboxList = [ { id:0, label:"uppercase", name: "upper", checked:false }, { id:1, label:"lowercase", name: "lower", checked:false }, { id:2, label:"number", name: "number", checked:false }, { id:3, label:"symbol", name: "symbols", checked:false } ] const PasswordGenerator = () => { const [data, setData] = useState(checkboxList) const handleChange = (id:number) => { const updateCheckboxes = checkboxList.map((checkbox) => checkbox.id === id ? {...checkbox, checked: !checkbox.checked}:checkbox) setData(updateCheckboxes) } return ( <div className="elements"> {data.map((obj) => { return( <div key={obj.id}> <Checkbox multiple={true} id={obj.id} label = {obj.label} checked= {obj.checked} name= {obj.name} onChange = {() => handleChange(obj.id)} /> </div> ) })} </div> ) }</pre> <p><br /></p>
P粉729198207
P粉729198207

reply all(1)
P粉662361740

When you update the state, you are updating from the original array rather than the current state. Instead of mapping from the original array (checkboxList), map from the current value of the state (data):

const handleChange = (id:number) => {
  const updateCheckboxes = data.map((checkbox) => 
    checkbox.id === id ? {...checkbox, checked: !checkbox.checked}:checkbox)

  setData(updateCheckboxes)
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template