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?
Asked
Active
Viewed 938 times
3
-
1What have you tried so far? This sounds like the stock standard react forms approach. – Dominik Apr 21 '21 at 08:42
-
i had tried to store the values of checkbox in a separate useState variable initialised to 0,then checked if checkBox1value>0 then setAllcheckbox(old=>{...old,checkBox1value}) similarly checked for the other checkboxes. – Rk Kk Apr 21 '21 at 19:28
2 Answers
2
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}
/>

Vladut
- 58
- 5
-
This worked great! Thanks! I implemented it slightly differently without a Checkbox but with a Pressable. – teewuane Nov 22 '22 at 21:52
0
You can make it multiple ways. You can just make const checkboxOpenArray = []
where you will just store boolean values like [true, false, false, true]
so later in the code where you probably .map
through all checkboxes you just check if checkboxOpenArray[idx]
where idx
you get from .map
. If it is true you just set checkbox to true. Same for onChange
- you just find idx
in the checkboxOpenArray
and set it to false or true.

Sowam
- 1,674
- 3
- 12
- 30