I'm trying to retrieve the checked value of a checkbox and save it into an array. I tried:
arr.push(setNewItem(checked)) arr.push(e.target.value.checked) arr.push(items.checked)
But these return values of the wrong type or undefined.
const [checkedItems, setCheckedItems] = useState([]); const handleChange = (e) => { if (e.target.checked) { var arr = [...checkedItems]; //arr.push(setNewItem(e.target.value.checked)); setCheckedItems(arr); console.log(arr); } else { checkedItems = ""; } setIsChecked((current) => !current); };
return ();setNewItem(e.target.value)} onKeyPress={handleOnKeyPress} /> addItem()}>Add {items.map((item) => { return ( ); })} {item.value} {""} deleteItem(item.id)}> X
This may solve your problem.
is the correct way to get rid of:
You cannot update status this way, and when you try to uncheck an input, an error will appear:
Now let's see what you want to do, every time an input is checked, you store
e.target.checked
, socheckedItems
will look like this:Why do you need this? A better approach is to store the id of the selected item:
Then in jsx:
Now look at this:
You are mapping via
items
, creating multiple checkboxes, but they all share the same value. The value attribute of the checkbox is not what you think, please learn more inhere. So you can usevalue={item.id}
to set a unique value for each input, and get rid of the useState hook ofisChecked
, which you don't really need.