How to Add and Remove Checkbox Values to an Array in React
In this lesson, we are going to see how to add and remove checkbox values to an array in react js, we are going to use react hooks to do that.
Create the component
First, let's create the component and display the checkboxes.
import React from 'react';
export default function FilterChecks() {
const [filterParams, setFilterParams] = useState([]);
const filterCheckboxs = [
{
id: 'check1',
label: 'Hot deal',
value: 'special_deals'
},
{
id: 'check2',
label: 'Special offer',
value: 'special_offer'
},
{
id: 'check3',
label: 'New',
value: 'new'
},
{
id: 'check4',
label: 'Best seller',
value: 'featured'
}
];
return (
<ul className="list-group">
{
filterCheckboxs.map(filter => (
<li key={filter.id} className="list-group-item">
<div className="form-check flex-grow-1">
<input
className="form-check-input"
type="checkbox"
value={filter.value}
onChange={(e) => console.log(e)}
id={filter.id}
checked={filterParams.params.find(item => item === filter.value)} />
<label className="form-check-label" htmlFor={filter.id}>
{ filter.label }
</label>
</div>
</li>
))
}
</ul>
)
}
Add and remove checkbox values to the array
Next, we add the function to add and remove the values to the array.
import React from 'react';
export default function FilterChecks() {
const [filterParams, setFilterParams] = useState([]);
const handleInputChange = (e) => {
let exists = filterParams.find(filter => filter === e.target.value);
if(exists) {
const updatedFilters = filterParams.filter(filter => filter !== e.target.value);
setFilterParams(updatedFilters);
}else {
setFilterParams([...filterParams.params, e.target.value])
}
}
const filterCheckboxs = [
{
id: 'check1',
label: 'Hot deal',
value: 'special_deals'
},
{
id: 'check2',
label: 'Special offer',
value: 'special_offer'
},
{
id: 'check3',
label: 'New',
value: 'new'
},
{
id: 'check4',
label: 'Best seller',
value: 'featured'
}
];
return (
<ul className="list-group">
{
filterCheckboxs.map(filter => (
<li key={filter.id} className="list-group-item">
<div className="form-check flex-grow-1">
<input
className="form-check-input"
type="checkbox"
value={filter.value}
onChange={(e) => handleInputChange(e)}
id={filter.id}
checked={filterParams.params.find(item => item === filter.value)} />
<label className="form-check-label" htmlFor={filter.id}>
{ filter.label }
</label>
</div>
</li>
))
}
</ul>
)
}