How to add button in a specific node of react Sortable Tree

Viewed 5710

I'm working with react library 'react-sortable-tree' and I don't know how to add buttons only to a certain type of nodes. For example the element in a node has a specific value I need to add a button for do something.

                <SortableTree
                    canDrop={canDrop}
                    getNodeKey={({ node }) => node.id}
                    treeData={this.state.treeData}
                    onChange={this.onChange}
                    generateNodeProps={({ node, path }) => ({
                        title: (
                            <a href={node.url}>{node.title}</a>
                        ),
                    })}
                />

What can I add to this component in order to add a button only in some specific case?

EDIT

Artistic example

The idea is to add a button only when the node is a Web Content

Actualy I make it in this way:

generateNodeProps={({ node, path }) => ({
title: (
    <Row>
        <Col xs={6} sm={6} md={6} lg={6}>
            <a href={node.url}>{node.title}</a>
        </Col>
        <Col xs={6} sm={6} md={6} lg={6}>
            {node.isWebContent &&
                <DefaultButton text='Open editor' />
            }
        </Col>
    </Row>
),
})}

and this is the result:

result

There isn't a better way to do this? a good pratice, like not use the title property?

2 Answers

You can use generateNodeProps to add buttons to rendered elements. There is a dedicated buttons prop (I checked in versions 2.5.2 and 2.2.0 but I believe it was available earlier as well). Example:

<SortableTree
    canDrop={canDrop}
    getNodeKey={({ node }) => node.id}
    treeData={this.state.treeData}
    onChange={this.onChange}
    generateNodeProps={extendedNode => ({
        title: (
            <a href={extendedNode.node.url}>{extendedNode.node.title}</a>
        ),
        buttons: extendedNode.node.title === "Web Content" ? [<button>X</button>] : [],
    })}
/>

I have no idea what your code looks like, but could a function like this make sense for you?

            renderButton = (title) => {
               return title === 'Web Content' ? <button>Your button</button> : null
            }


            <SortableTree
                canDrop={canDrop}
                getNodeKey={({ node }) => node.id}
                treeData={this.state.treeData}
                onChange={this.onChange}
                generateNodeProps={({ node, path }) => ({
                    title: (
                        <a href={node.url}>
                          {node.title}
                          {renderButton(node.title)}
                        </a>
                    ),
                })}
            />
Related