I have some checkboxes displayed using .map() function which is retrieving the data from a JSON file.
What i have achieved so far, is to store the clicked checkbox into the state (which is an object). But after I click another checkbox, it removes the previous one and store the latest..
I basically want to store all the checked ones, and if you remove them to remove it from the state.
Here's my handleCheck() function:
const handleCheckInput = (
e: React.ChangeEvent<HTMLInputElement>,
key: number,
questionId: number,
) => {
let newTickArray = [...tick];
newTickArray[key] = !tick[key];
setTick(newTickArray);
setValues({ ...values, [questionId]: e.target.value });
};
Any help will be appreciated
Changed [questionId]: e.target.checked to [questionId]: e.target.value.
Here is how you do it (I used ellipsis ... for parts that don't need to be changed and also for brevity):
(Also remember to use e.target.checked - the right property for checkbox elements - instead of e.target.value).
const handleCheckInput = (
e: React.ChangeEvent<HTMLInputElement>,
key: number,
questionId: number) => {
...
if (e.target.checked) {
setValues({ ...values, [questionId]: e.target.value});
} else {
// Remove unchecked from state.
let { [questionId]: deletedKey, ...restOfObj } = values;
setValues(restOfObj);
}
};