Search code examples
javascriptreactjstreeview

adding treeNode to antdesign tree


I wrote this Code and I want to add 3 icons per each record in this antDesign tree.so what should I do? i tried lots of ways but idk what is the solution

const ChartMaker = ({ chart }) => {
    const [parentId, setParentId] = useState(null)
    const [childId, setChildtId] = useState(null)

    const flattenData = (data) => {
        if (!data) return [];
        return data.map((item) => ({
            title: item.title,
            key: item.id,
            children: flattenData(item.childs, flattenData(item.child))
        }));
    };
    const treeData = flattenData(chart);

    const onSelect = (selectedKeys) => {
        setChildtId(selectedKeys)
    };
    const onExpand = (keys) => {
        setParentId(keys)
    };
    console.log("parent", parentId, "child", childId);
    return (
        <Tree
            showLine
            switcherIcon={<DownOutlined />}
            onSelect={onSelect}
            onExpand={onExpand}
            treeData={treeData}
        >
            <TreeNode icon={<DeleteOutlined />} />
        </Tree>
    );
};
export default ChartMaker;

Solution

  • As per the Ant Design docs, you have to pass a props in tree component to show icons along side each child in the tree. For this, lets modify the server data to include icon property like so:

    const flattenData = (data) => {
        if (!data) return [];
        return data.map((item) => ({
            title: item.title,
            key: item.id,
            // Add an Icon property here for childs
            icon: item.childs ? <FolderOutlined /> : item.child ? <FolderOutlined /> : <DeleteOutlined />, 
            children: flattenData(item.childs, flattenData(item.child))
        }));
    };
    

    Your component Tree should look like this:

    return (
        <Tree
            showLine
            switcherIcon={<DownOutlined />}
            onSelect={onSelect}
            onExpand={onExpand}
            treeData={treeData}
        >
        </Tree>
    );
    

    And with this, you should see relevant icons in the component tree.