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 linmic

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.min.js "></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/classnames/2.2.3/index.min.js"></script>
<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>

<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>

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;
}

JavaScript 1.7

/**
 * Using React 0.14.7
 *
 * - 2016-02-16: Update to React 0.14.7, ReactDOM, Babel
 * - 2015-04-28: Update to React 0.13.6
 */

var TreeNode = React.createClass({
  getInitialState: function() {
    return {
      visible: true
    };
  },
  render: function() {
    var childNodes;
    var classObj;

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

      classObj = {
        togglable: true,
        "togglable-down": this.state.visible,
        "togglable-up": !this.state.visible
      };
    }

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

    return (
      <div>
        <h5 onClick={this.toggle} className={classNames(classObj)}>
          {this.props.node.title}
        </h5>
        <ul style={style}>
          {childNodes}
        </ul>
      </div>
    );
  },
  toggle: function() {
    this.setState({visible: !this.state.visible});
  }
});

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

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