mercredi 6 avril 2022

Remove the checked item from the checkbox array in Reactjs

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.

enter image description here

How to do it correctly?




Aucun commentaire:

Enregistrer un commentaire