ReactJS parent-child component lifecycle
A demonstration of how the "componentDidUpdate" and "componentDidMount" lifecycle methods are ordered when rendering nested React components
HTML
<script src="http://fb.me/JSXTransformer-0.10.0.js"></script>
<script src="http://fb.me/react-with-addons-0.10.0.js"></script>
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
JavaScript 1.7
/** @jsx React.DOM */
var Child = React.createClass({
componentDidMount: function() {
console.log("Child " + this.props.count + " mounted");
},
componentDidUpdate: function() {
console.log("Child " + this.props.count + " updated");
},
render: function() {
return <h2>{this.props.count}</h2>;
}
});
var Parent = React.createClass({
getInitialState: function() {
return { count: 0 };
},
componentDidMount: function() {
console.log("Parent mounted");
},
componentDidUpdate: function() {
console.log("Parent updated");
},
onClick: function(e) {
this.setState({ count: this.state.count + 1 });
},
render: function() {
var children = [],
i;
for (i = 0; i < this.state.count; i++) {
children.push(<Child count={i} key={i} />);
}
return (
<div>
<button onClick={this.onClick}>Add child</button>
{children}
</div>
);
}
});
React.renderComponent(<Parent />, document.body);