I've been looking around different answers but all of them are jQuery related or very complex for what I have in mind? I am working in a form and want that when user checks a box, its value should be added to an array storing info in the parent component. If box is unchecked, remove that item from array.
Code trimmed for simplicity
const Knowledge = (props) => {
const checkHandler = (e) => {
const tools = props.data.usesTools; //Array in parent component
const value = e.target.value; //Checkbox value
tools.includes(value) //If Array contains value
? tools.filter((tool) => tool.value != value) // Then remove item from Array
: tools.push(value) // Else, push item to Array;
};
return (
<div>
<label>
<input
type="checkBox"
name="usesTools"
value="Slack"
onChange={checkHandler}
/>
Slack
</label>
</div>
//Other checkboxes removed for simplicity
)
}
Questions:
1) How to add/remove items to Array if checkbox is selected/not selected.
2) I Tried adding a hook to check/uncheck the box but its checking all the boxes as soon the handler is called:
const [ isSelected, setSelected = useState(false);
<input
type="checkBox"
name="usesTools"
value="Slack"
onChange={checkHandler}
checked={isSelected}
/>