React-sortable-tree: How to duplicate/clone nodes?

Created on 16 Nov 2017  路  6Comments  路  Source: frontend-collective/react-sortable-tree

Can anyone recommend what the best way to implement a button that when clicked clones a node in the current level of the tree?

Before clicking the button
image

After clicking the button
image

Most helpful comment

@fritz-c I'm not 100% sure i understood what you mean, but this is how i ended up solving it (with addNodeUnderParent):

<button
    onClick={() =>
    {
        this.setState(state => ({
        treeData: addNodeUnderParent({
        treeData: state.treeData,
        parentKey: path[path.length - 2], //the "-2" adds the new node as a sibling, if it was "-1" it will add it as a child
        expandParent: true,
        getNodeKey,
        newNode: {
            title: node.title, //the new node's title should be the same as the clicked one
            subtitle: node.subtitle //the new node's subtitle should be the same as the clicked one
        }
        }).treeData
    }))}}
>Clone</button>

All 6 comments

just create a custom function that is bound to the clone button that just inserts the node into the treeData

Use either changeNodeAtPath or addNodeUnderParent, combined with the path (subtracting the last entry to get the parent path) value you鈥檙e given by the prop mapping api.

@fritz-c I'm not 100% sure i understood what you mean, but this is how i ended up solving it (with addNodeUnderParent):

<button
    onClick={() =>
    {
        this.setState(state => ({
        treeData: addNodeUnderParent({
        treeData: state.treeData,
        parentKey: path[path.length - 2], //the "-2" adds the new node as a sibling, if it was "-1" it will add it as a child
        expandParent: true,
        getNodeKey,
        newNode: {
            title: node.title, //the new node's title should be the same as the clicked one
            subtitle: node.subtitle //the new node's subtitle should be the same as the clicked one
        }
        }).treeData
    }))}}
>Clone</button>

@borisyordanov thanks for the code!
The behavior I get with your code, is that it doesn't copy the child nodes of the node from which you click "clone".
Is there a way you think, to include all the subnodes as well?

@mariovde I haven't used this library in a while. I think there was a way to include all the subnodes, but not sure what it is any more

Thanks for the reply, I already solved it by doing newNode: {...node }.

Was this page helpful?
0 / 5 - 0 ratings