lukasbach / react-complex-tree

Unopinionated Accessible Tree Component with Multi-Select and Drag-And-Drop
https://rct.lukasbach.com
MIT License
952 stars 77 forks source link

How to add/delete a tree data node ? Can a slot be provided #222

Closed wanjinji closed 1 year ago

wanjinji commented 1 year ago

Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like A clear and concise description of what you want to happen.

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

Additional context Add any other context or screenshots about the feature request here.

lukasbach commented 1 year ago

See #87

wayne1203 commented 1 year ago

See #87

I tried to use "ControlledTreeEnvironment" and suppose I have full control of the tree data. In my situation, I have a param called "defaultTreeData" to save original tree data. First, I'm trying to add one node key "new-0", and reset the tree data by setState(defaultTreeData) (The tree is reset to default in UI). After that, I add the node key "new-0" again, it will occur "Encountered two children with the same key," and show 2 "new-0" in UI.

const onResetNode = () => {
    setTreeData(defaultTreeData);
}

// Call from "renderItem"
const onAddNode = (item) => {

    const temp = { ...treeData };

    const nodeId = item.index;
    const parentId = Object.values(temp).find(o => o.children.includes(nodeId)).index;

    const prefix = "new-";
    const count = Object.keys(temp).filter(o => o.match(prefix)).length;
    const newNodeId = `${prefix}${count}`;

    temp[`new-${count}`] = {
        index: newNodeId,
        canMove: true,
        isFolder: true,
        children: [],
        data: {
            id: newNodeId,
            name: `New Location ${count}`
        }
    }

    // Add node to current node children
    temp[nodeId].children = [
        newNodeId,
        ...temp[nodeId].children
    ];

    setTreeData(temp);
}