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 rajeshpillai
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/classnames/2.2.3/index.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.12.0/babel.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 15.3.0
*
* - 2016-08-12: Update to React 15.3.0, class syntax
* - 2016-02-16: Update to React 0.14.7, ReactDOM, Babel
* - 2015-04-28: Update to React 0.13.6
*/
class TreeNode extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true,
};
}
toggle = () => {
this.setState({visible: !this.state.visible});
};
render() {
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>
);
}
}
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")
);