jakezatecky / react-checkbox-tree

A simple and elegant checkbox tree for React.

Home Page:https://jakezatecky.github.io/react-checkbox-tree/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Show until specific level in tree

elcirao opened this issue · comments

Please include a clear and concise description of the feature or enhancement you would like to have added to the project.
Hi, is there a way to show until specific leven in the tree? For example, i have an array with four levels from the API, but i just want to show until the third level. Is that possible?

To be clear, are you looking for something to expand all of the nodes until the third level? This is a reasonable enough request, but it can be done through the expanded property, by iterating recursively through nodes until the desired depth is reached.

I can potentially add a utility function to help set that initial state.

yes, i want expand all of the nodes until the third level :)

For the interim, you can do something like the following. Note that the first level starts with 0:

function expandNodesToLevel(nodes, targetLevel, currentLevel = 0) {
  if (currentLevel > targetLevel) {
    return [];
  }

  let expanded = [];
  nodes.forEach((node) => {
    expanded.push(node.value);
    if (node.children) {
    	expanded = [...expanded, ...expandNodesToLevel(node.children, targetLevel, currentLevel + 1)];
    }
  });
  return expanded;
}

For the initial state, you would do something like expanded = expandNodesToLevel(nodes, 2);.

See the following example that expands the tree to the second level.

it works perfect!