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!