Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push a number in useState array

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?

like image 634
Rk Kk Avatar asked Feb 14 '26 23:02

Rk Kk


1 Answers

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}
/>
like image 179
Vladut Avatar answered Feb 16 '26 12:02

Vladut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!