search

Home  >  Q&A  >  body text

Why does clicking a checkbox cancel the previous selection in React?

<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粉729198207P粉729198207501 days ago705

reply all(1)I'll reply

  • P粉662361740

    P粉6623617402023-08-14 09:26:59

    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)
    }

    reply
    0
  • Cancelreply