I have a list of checkboxes.
I need to implement the select all check box.
Design:
I tried implementing the same but when I am achieving one of the functionalities (mainly 3,4) I am losing the other.
The core Select all implementation remains the same for all component libraries.
You just need to use the props provided by the component accordingly. Let's say here we are using options
to pass all the checkbox options in <Checkbox.Group/>
it may be items/ the implementation would be different. Ex: See the Checkbox Group implementation in Chakra UI
You need two states one for checkedList options and one for storing checkAll state(boolean
).
const [checkedList, setCheckedList] = useState([]);
const [checkAll, setCheckAll] = useState(false);
Your case 1,2 are handled by the onChange of checkbox Check All
and case 3,4 are handled by the onChange of <Checkbox.Group/>
const onChange = (list) => {
setCheckedList(list);
setCheckAll(list.length === checkboxOptions.length);
};
const onCheckAllChange = (e) => {
setCheckedList(e.target.checked ? checkboxOptions : []);
setCheckAll(e.target.checked);
};
The corresponding JSX is below
<Checkbox onChange={onCheckAllChange} checked={checkAll}>
Check all
</Checkbox>
<Checkbox.Group options={checkboxOptions} value={checkedList} onChange={onChange} />
Check this sandbox for the working code snippet.