Search code examples
antd

How to uncheck all child nodes but parent node is still checked and vice versa?


I'm using AntD V5, currently I have a Tree like this Tree I want its behavior to be:

  1. When I click the parent node, all its child nodes are checked (this is working)
  2. When I uncheck all checked child nodes, their parent node is still checked.
  3. When nothing is checked, when I check all child nodes of a parent node, that node is not checked.

Current only the number 1 work.

I tried this but it only unlinks the parent node to all its child nodes

checkStrictly={true}

This is a working example of Antd Tree demo


Solution

  • I finally got it worked! Below is my onCheck function to pass into Antd Tree

    const onCheck = (e, info) => {
      const checkedChildrenKeys: (string | number)[] = [];
      const unCheckedChildrenKeys: (string | number)[] = [];
      const checkedCallback = (e: DataNode) => {
        checkedChildrenKeys.push(e.key);
        e.children && e.children.forEach(checkedCallback);
      };
      const uncheckedCallback = (e: DataNode) => {
        unCheckedChildrenKeys.push(e.key);
        e.children && e.children.forEach(uncheckedCallback);
      };
      if (info.checked) {
        if (!info.node.children) {
          setCheckedKeys([...e.checked]);
          return;
        }
        info.node.children.forEach(checkedCallback);
        setCheckedKeys([...e.checked, ...checkedChildrenKeys]);
      } else {
        info.node.children?.forEach(uncheckedCallback);
        const uncheckedList = e.checked.filter(
          (key: any) => !unCheckedChildrenKeys?.includes(key)
        );
        setCheckedKeys(uncheckedList);
      }
    };
    

    I have updated my codesandbox to demonstrate it. Thanks!