Stefano
Stefano

Reputation: 302

How to load and open programmatically tree nodes using React and antd Tree?

My tree is made with React and I use the Ant Design Tree that loads data asynchronously.
I have a search input at the top of the tree and, when the user search something, I want to load and open the first result of the search after that I queried the database and I find the paths of the nodes. I didn't find native functions in antd.

This is my tree (the same as https://ant.design/components/tree/)

<Tree
   loadData={this.onLoadData}
   showLine
   onExpand={this.onExpand}
   expandedKeys={expandedKeys}
>
    {this.renderTreeNodes(this.state.treeData)}
</Tree>

And my renderTreeNode function

renderTreeNodes = (data) => {
    return data.map((item) => {
        if (item.children) {
            return (
                <TreeNode
                    title={<Nodo item={item} openNode={this.openNode} />}
                    key={item.key}
                    dataRef={item}
                >
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode
            {...item}
            title={<Nodo item={item} openNode={this.openNode} />}
            key={item.key}
            dataRef={item}
        />;
    });
}


How can I achieve this?

Upvotes: 1

Views: 9358

Answers (2)

Maksim Nesterenko
Maksim Nesterenko

Reputation: 6213

I want to load and open the first result of the search after that I queried the database and I find the paths of the nodes

Use tree in a controllable way. Pass expandedKeys prop to it and track its state in the parent component.

function Parent() {
  const [expandedKeys, setExpandedKeys] = React.useState([])
  return <Tree expandedKeys={expandedKeys} onExpand={setExpandedKeys} />

Alternatively, you can wait with a render of the tree unless you have initial data and then pass defaultExpandedKeys to it.

see https://ant.design/components/tree/#Why-defaultExpandedAll-not-working-on-ajax-data

Upvotes: 1

Stefano
Stefano

Reputation: 302

I made a button to open the root on click. And this is the function.

var { treeData } = this.state;
var _this = this;

return new Promise((resolve) => {
    _this.setState({
        loading: true
    });
    query
         then((response) => {
               // I set the children of the first item, which is the root
               treeData[0].children = response.map((item)=>{
                   return { ...item, key: item.key };
                });
                // I set the expanded  keys of the tree
                _this.setState({
                    treeData: treeData,
                    loading:false,
                    expandedKeys: ["root"]
                });
                resolve();
           })
           .catch((err) => {
                console.warn('ERR TreeQuery:', err);
           });
  });

Upvotes: 2

Related Questions