I have created a checkbox array that stores the checked items array, it should be like when the item is checked it's stored in an array and when the item unchecked the remove from the array.
<input
className="border border-2 "
type="checkbox"
value={`${items.VariationID}`}
defaultChecked={!!checked[items.VariationID]}
onChange={(e) => {
handleChange(e);
}}
/>
This is how I create the checked array
const handleChange = (e) => {
let updatedList = [...checked];
if (checked) {
updatedList = [...checked, e.target.value];
} else {
updatedList.splice(checked.indexOf(e.target.value), 1);
}
setChecked(updatedList);
console.log(updatedList);
};
but the result I get is when I checked the item is added to the check array but when unchecked the check box it didn't remove it from the array instead it add-in again.
How to do it correctly?
CodePudding user response:
You should use e.target.checked
not checked
.
const handleChange = (e) => {
let updatedList = [...checked];
// if (checked) { <- this part, checked is the array of checked item right?
if(e.target.checked) {
updatedList = [...checked, e.target.value];
} else {
updatedList.splice(checked.indexOf(e.target.value), 1);
}
setChecked(updatedList);
console.log(updatedList);