Kevin Zheng
Kevin Zheng

Reputation: 45

react create dynamic tree recursively

thanks for reading and helping. Here is my situation so far:

  1. I have much data in database, each piece of data has id, parentid(which means you can find the id of its parent using this parentid ), name, description.

  2. I want to create a dynamic tree using react,but I do not know how many levels of nodes I have. Each node represents for an id in database. An user clicks on a node A on this tree, the children nodes whose parentid equals to A's id will show/hide.

  3. I do not intend to retrieve all the data because it will take long time. Now I am able to get one node's children by sending request and get response.body:

     getChildren(id){
        ajax.get('http://localhost:8080/configmgmt/code/category/retriveTree/' + id)
       .end((error, response) => {
       if (!error && response) {
       console.dir(response.body );
       this.setState(subdata:response.body});
    
    } else {
       console.log('There was an error fetching from database', error);
        }
       }
     );
    }
    
  4. in render part, I wrote:

       {this.state.subdata.map((rb,index)=>{
                return  <li><div><a href='##' onClick = {this.getChildren.bind(this,rb.id)}><em></em><label className="one_title">{rb.name}</label></a></div></li>})
        }
    

Here comes the question, I still do not know how to create the tree recursively(because any node might has its children nodes ). how to do this when we can only get a node's children nodes from the database?

Upvotes: 1

Views: 5876

Answers (1)

Konstantin Solomatov
Konstantin Solomatov

Reputation: 10332

I would do your task in two steps:

  • Create a structure for an augmented tree with loading status flags. It should have a structure like this (this is pseudocode):

    class Node {
       loaded: boolean,
       expanded: boolean,
       children: list<Node>
    }
    
  • Create a component for this:

    • If node isn't expanded don't render its children
    • If use clicks on expand sign
    • If children are loaded, do nothing, just change the expanded field
    • If children aren't loaded
      • set expanded to true
      • initiate ajax request
      • as soon as the request completes, set loaded to true, and assign children

Creating a component which recursively uses itself isn't a problem. If you don't know how to do this read here: how to render child components in react.js recursively

Upvotes: 1

Related Questions