Answer the question
In order to leave comments, you need to log in
How to make a "Select all" button for checkboxes in React?
At first, it seemed to me that the task was one of the trivial ones, but then problems began to run into it ...
In general, I wanted to make the simplest button for selecting all checkboxes, but it’s impossible to do everything correctly so that when wrung out from the eventSkills array, the necessary ones are cleared and on the contrary, it’s problematic even to google something like this, there is very little material, so I hope for your help, preferably with an example
import React from 'react';
import {Field, Form, Formik} from 'formik';
const CheckBoxes = () => {
const mockSkills = [
{
id: 1,
name: 'Skill 1'
},
{
id: 2,
name: 'Skill 2'
},
{
id: 3,
name: 'Skill 3'
},
]
return (
<div className="app-content">
<Formik
initialValues={{eventSkills: []}}
onSubmit={() => null}>
{({values, handleChange, handleSubmit}) => (
<Form onSubmit={handleSubmit}>
<div className="form-group">
<div className="form-row mr-4 w-100">
<pre className="d-flex">
eventSkills: {values.eventSkills.map(el => (
<div className="mr-3">
id: {el}
</div>
))}
</pre>
<label className="mb-2">Required skills</label>
<div className="required-skills-column" role="group"
aria-labelledby="checkbox-group">
<label className="d-block mb-1 select-all custom-checkbox">
<Field
type="checkbox"
name="eventSkills"
value={mockSkills}
onChange={handleChange}
/>
<span className="ml-2">Select all</span>
</label>
{
mockSkills?.map((el) => (
<label key={el.id}
className="d-block mb-1 custom-checkbox">
<Field
type="checkbox"
name="eventSkills"
value={`${el.id}`}/>
<span className="ml-2">{el.name}</span>
</label>
))
}
</div>
</div>
</div>
</Form>
)}
</Formik>
</div>
)
}
export default CheckBoxes;
Answer the question
In order to leave comments, you need to log in
<Field
type="checkbox"
name="selectAll"
/>
<span className="ml-2">Select all</span>
<Formik ... initialValues={{eventSkills: [], selectAll: false}}>
{({values, handleChange, setFieldValue, handleSubmit}) =>
React.useEffect(() => {
if (values.selectAll) {
setFieldValue('eventSkills', mockSkills.map(({ id }) => id));
} else {
setFieldValue('eventSkills', []);
}
}, [values.selectAll])
return (
<Form ... />
.....
)
}}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question