Want to manage state in a tree component in reactjs? I wanted to try out the tree structure with React and came up with a simple component that hides subtrees when you click on
TreeNode.jsx:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | var TreeNode = React.createClass({ getInitialState: function() { return { visible: true }; }, render: function() { var childNodes; if (this.props.node.childNodes != null) { childNodes = this.props.node.childNodes.map(function(node, index) { return <li key={index}><TreeNode node={node} /></li> }); } var style = {}; if (!this.state.visible) { style.display = "none"; } return ( <div> <h5 onClick={this.toggle}> {this.props.node.title} </h5> <ul style={style}> {childNodes} </ul> </div> ); }, toggle: function() { this.setState({visible: !this.state.visible}); } }); |
bootstrap.jsx:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var tree = { title: "howdy", childNodes: [ {title: "bobby"}, {title: "suzie", childNodes: [ {title: "puppy", childNodes: [ {title: "dog house"} ]}, {title: "cherry tree"} ]} ] }; React.render( <TreeNode node={tree} />, document.getElementById("tree") ); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.