'Antd React - How can i check all tree nodes with a select all checkbox?

I want to be able to check all tree node when i check the Check all checkbox, this is an example below : enter image description here

This is my code, have you any idea which state should I change please ? Thank you!



Solution 1:[1]

You can handle all cases like this with custom checkbox.

  let getAllKeys = (tree) => {
    let result = [];
    tree.forEach((x) => {
      let childKeys = [];
      if (x.children) {
        childKeys = getAllKeys(x.children);
      }

      result.push(...[x.key, ...childKeys]);
    });

    return result;
  };

  const allKeys = getAllKeys(treeData);

  const onChange = () => {
    if (checkedKeys.length === allKeys.length) {
      setCheckedKeys([]);
    } else {
      setCheckedKeys(allKeys);
    }
  };

JSX

     <Checkbox
        onChange={onChange}
        checked={checkedKeys.length === allKeys.length ? true : false}
      >
        Select All
      </Checkbox>

Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1