Search code examples
reactjscheckboxcomponentsantd

How to implement check all functionality for Ant Design check box


I have a list of checkboxes.

I need to implement the select all check box.

Design:

  1. When this check box is checked all the checkboxes should be checked.
  2. When this check box is unchecked all the checkboxes should be unchecked.
  3. When this checkbox is checked and some other checkbox is unchecked then this checkbox must be unchecked.
  4. When all the checkboxes are checked individually this checkbox must be checked.

I tried implementing the same but when I am achieving one of the functionalities (mainly 3,4) I am losing the other.


Solution

  • Select all checkbox implementation

    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

    Select All Checkbox implementation using Ant Design

    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.