I am creating a form where I have a group of checkboxes.
When click on checkbox, I would get the value of that specific checkbox and add to an Array (I am using the useState hook) and if I uncheck it will remove that element from the array.
That's my code so far:
const ContactUs = () => {
const [cities, setCities] = useState([])
useEffect(() => {
console.log(cities)
})
const handleCheck = (e) => {
if (e.target.checked) {
setCities([...cities, e.target.value])
} else {
removeCities()
}
}
const removeCities = () => {
setCities(() => cities.splice(DT.length - 1, 1))
}
return (
<Content>
<form>
<SectionTitle>Day Tours</SectionTitle>
<Checkbox
type="checkbox"
id="1"
label="Dublin"
value="dublin"
name="dublin"
onChange={handleCheck}
/>
<Checkbox
type="checkbox"
id="2"
label="New York"
value="New York"
name="new-york"
onChange={handleCheck}
/>
<Checkbox
type="checkbox"
id="3"
label="Torino"
value="Torino"
name="torino"
onChange={handleCheck}
/>
</form>
</Content>
)
}
I can add it to the array but I can't seem to remove it (or remove the right one).
I tried splice and slice methods but as I don't fully grasp their concept.