Reputation: 67
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.
Upvotes: 1
Views: 970
Reputation: 661
I don't know what is DT
as you haven't shared your whole code, but I think you can approach this in another still functional, declarative way:
Filter out the array so it returns everything that is checked and filters (removes) the unchecked ones:
in your else block:
setCities(cities.filter(city => city !== e.target.value))
Filter will always return a new array with the values that match the filter criteria, in this case it would return everything except the e.target.value
, which is what we want as based on your logic, the else block will execute when it's unchecked.
Upvotes: 1