A Tree structure in React JS

Every element in the tree is a TreeNode including the root itself. This demonstrates React components containing other instances of themselves.

by Ross Allen

HTML

<h3>It's <code>TreeNodes</code> all the way down</h3>
<p>Edit the <code>tree</code> variable to change the tree</p>
<div id="tree"></div>

CSS

body {
  font-family: "Helvetica Neue";
}

h3 {
  color: #BF616A;
}

.togglable {
  color: #D78770;
  cursor: pointer;
}

.togglable-down::after,
.togglable-up::after {
  font-size: 8px;
  margin-left: 0.5em;
}

.togglable-down::after {
  content: "▼";
  display: inline-block;
}

.togglable-up::after {
  content: "▶";
  display: inline-block;
}

React

class TreeNode extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    	visible: true,
    };
  }
  
  toggle = () => {
    this.setState({visible: !this.state.visible});
  };
  
  render() {
  	var childNodes;
    var className;

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

			className = 'togglable';
      if (this.state.visible) {
        className += ' togglable-down';
      } else {
        className += ' togglable-up';
      }
    }

    var style;
    if (!this.state.visible) {
      style = {display: "none"};
    }

    return (
      <div>
        <h5 onClick={this.toggle} className={className}>
          {this.props.node.title}
        </h5>
        <ul style={style}>
          {childNodes}
        </ul>
      </div>
    );
  }
}

var tree = {
  title: "howdy",
  childNodes: [
    {title: "bobby"},
    {title: "suzie", childNodes: [
      {title: "puppy", childNodes: [
        {title: "dog house"}
      ]},
      {title: "cherry tree"}
    ]}
  ]
};

ReactDOM.render(
  <TreeNode node={tree} />,
  document.getElementById("tree")
);