In a form having multiple checkbox, I want to store the values of the check box in an useState array after clicking submit. Also the user may check/uncheck a check box multiple times before submitting the form. What can be the approach/code?
Every checkbox have a "checked" property, so in state you must have an array with all the checked checkboxes.
const [selectedCheckboxes, setSelectedCheckboxes] = useState([]);
For example you might store also the checkboxes on an array:
const checkboxes = [{name: 'cb1', label:'cb1'}, {name: 'cb2', label:'cb3'}, ...];
and all of them should have the same onChange method:
onCheckBoxChange = (event) => {
const selectedCheckboxes = [...selectedCheckboxes];
const isChecked = selectedCheckboxes.includes(event.target.name);
if (!isChecked) {
selectedCheckboxes.push(event.target.name);
} else {
selectedCheckboxes.splice(selectedCheckboxes.indexOf(event.target.name), 1);
}
setSelectedCheckboxes(selectedCheckboxes);
};
a common function that verify if a checkbox is checked:
isChecked = (cb) => selectedCheckboxes.includes(cb.name);
and every checkbox should look like:
<CheckBox
name={cb.name}
checked={isChecked(cb)}
onChange={onCheckBoxChange}
{...props}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With