Skip to content
Advertisement

React treeview from JSON array

I am making a treeview from JSON using react. So far I have made a collapsible tree using this example data:

var data = {
      title: "Node 1",
      childNodes: [
        {title: "Childnode 1.1"},
        {title: "Childnode 1.2",
          childNodes: [
            {title: "Childnode 1.2.1",
              childNodes: [
                {title: "Childnode 1.2.1.1"}
              ]}, {title: "Childnode 1.2.2"}
          ]}
      ]
    };

But this is one object. I want to get JSON array of objects as input and generate treeview from that but I am unable to understand where to change the code.

Here’s my render function:

render() {
    var childNodes;

    if (this.props.node.childNodes != null) {
      childNodes = this.props.node.childNodes.map(function (node, index) {
        return <li key={index}><Treeview node={node}/></li>
      });
    }

    return (
      <form>
        <div>
          <input type="checkbox"/>
          <label for>{this.props.node.title}</label>
        </div>
        <ul>
          {childNodes}
        </ul>
      </form>

    );
  }

How can I change the code to work with the whole array and not just one object?

Advertisement

Answer

Recursion is fun!

const data = [{
  title: "Node 1",
  childNodes: [
    { title: "Childnode 1.1" },
    {
      title: "Childnode 1.2",
      childNodes: [
        {
          title: "Childnode 1.2.1",
          childNodes: [
            { title: "Childnode 1.2.1.1" }
          ]
        }, { title: "Childnode 1.2.2" }
      ]
    }
  ]
}];

const App = () => (
  <form>
    <Tree data={data} />
  </form>
);

const Tree = ({data}) => ( 
  <ul>
    {data && data.map(item => (
      <li>
        {item.title}
        {item.childNodes && <Tree data={item.childNodes} />}
      </li>
    ))}
  </ul>
);

Demo: https://codesandbox.io/s/01kl2xmo40

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement