rhysclay
rhysclay

Reputation: 1683

React recursive list depth

I have a list which renders recursively like so:

  renderHeirachy(heirachy, depth) {
    const list = heirachy.map((folder, index) => {
      let subList;

      if (folder.children && folder.children.length > 0) {
        depth++;
        subList = this.renderHeirachy(folder.children, depth);
      }

      return (
        <li key={index}>
          <Link className="w100 display-block" to={`?folder=${folder.slug}`}>
            <span className="typcn typcn-folder mr1"></span>
            {folder.name}
          </Link>
          {subList}
        </li>
      );
    });

    return (
      <ul className={'wbbroc-list-unstyled wbbroc-list-heirachy ' + 'test'}>
        {list}
      </ul>
    );
  }

However the problem with this is that when I have multiple children the depth figure gets thrown out, for example:

ul
 li -> depth = 1
 li -> depth = 2
ul
 li -> depth = 3

I really just want the depth of the recursion like this:

ul
 li -> depth = 1
 li -> depth = 1
ul
 li -> depth = 1

Upvotes: 0

Views: 281

Answers (2)

blaz
blaz

Reputation: 4068

The problem here is that you increment depth value for every child folder having children, which is not correct. The correct way is to not modify depth value, and pass depth + 1 to the recursive call instead.

  if (folder.children && folder.children.length > 0) {
    subList = this.renderHeirachy(folder.children, depth + 1);
  }

Upvotes: 0

Rafael Mora
Rafael Mora

Reputation: 1219

You have to use a BFS like algorithm like: https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/tutorial/

Upvotes: 1

Related Questions