简体   繁体   中英

Update state of multiple checkboxes in React with useState


I am quite new to react.js so please apologise if I am not getting everything on the first try.

My problem is that I do not understand how to update the state of a checkbox by using hooks.

This is the code I am using to generate my checkboxes (from react-bootstrap):

Checkbox Component :

        <Form.Group controlId="briefing">
          {['Component1', 'Component2', 'Component3', 'Component4'].map((component)=>(
            <Form.Check
              custom
              inline
              label={component}
              name={component}
              type="checkbox"
              id={`module-component-${component}`}
              onChange={(e)=>handleComponentChange(e)}
            />
          ))}
        </Form.Group>

handleComponentChange() :

const [inputs, setInputs] = useState({});

const handleComponentChange = (event) => {
  event.persist()

  setInputs(inputs=>({
    ...inputs,
    components:{
      ...inputs.components,
      name:event.target.name
    }
  }))  
}

the ...inputs comming from other input fields I have in this form.

This is not working how I would like to. The state is getting updated but overwritten by the last checked item:

    {
      "components":{
        "name":"Component1"
      },
        "customfield_10313":"Input 1",
        "customfield_10411":"Input 2",
        "customfield_10405":"Input 3",
        "customfield_10385":"input 4"
    }

What I would like to see as the result is something like this:

{
  "components":[
  {
     "name":"Component1"
  },
  {
     "name":"Component2"
  },
  {
     "name":"Component3"
  },
  {
     "name":"Component4"
  }
  ]
}

I need this structure for an API call.

I know that you need to check if the checkbox is already checked and then remove the item if so. That's my next problem.

Thank you for any input!

Since you want you components state to contain an array, you need to update it like one. Also you would need to make sure to remove items from list when you uncheck a checkbox ie when item was already in the array

const handleComponentChange = (event) => {
  event.persist()

  setInputs(inputs=>{
   // find it component is already there. If yes remove it
   const index = inputs.components.findIndex(item => item.name === event.target.name);
   if(index > -1) {
       return {
          ...inputs,
          components: [
            ...inputs.components.slice(0, index),
            ...inputs.components.slice(index + 1),
          ]
       }
    } else {
       // push item into array
       return {
          ...inputs,
          components: inputs.components.concat({name: event.target.name}),
       }
    }
  }) 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM