Home > Back-end >  Create Antd Tree based on checked Node of another Antd Tree
Create Antd Tree based on checked Node of another Antd Tree

Time:01-30

I want to create a Tree antd data with only checked nodes of another Tree data, please take a look here image

When I Check some nodes and click on validate, I want to be able to filter only checked/half checked data from my data and create another Tree with new data. This is my sandbox, please take a look :) https://codesandbox.io/s/modern-browser-glh4n?file=/index.js

Example with images : When i check this node and i click on validate : image when I select nodes , I expect to get this result : expected result Thank you

CodePudding user response:

I've created a recursive method to create new tree data based on checked and half checked tree nodes, actually it filters the original tree with it's sub tree.

here's the updated codesandbox :

const createNewTreeData = (treeData, checkedKeys) => {
  return treeData.reduce((acc, treeDataItem) => {
    if (checkedKeys.includes(treeDataItem.key)) {
      if (treeDataItem.children) {
        acc.push({
          ...treeDataItem,
          children: createNewTreeData(treeDataItem.children, checkedKeys)
        });
      } else {
        acc.push(treeDataItem);
      }
    }

    return acc;
  }, []);
};

And in onCheck event I've added halfchecked nodes to allChecked state like this:

onCheck = (checkedKeys, e) => {
    const allCheckedKeys = [...checkedKeys, ...e.halfCheckedKeys];
    this.setState((prevState) => ({
      ...prevState,
      allCheckedKeys,
      checkedKeys
    }));
};
  •  Tags:  
  • Related