componentWillReceiveProps demo

by Marcus Johnson

HTML

<script src="http://fb.me/react-with-addons-0.12.0.js"></script>
<script src="http://fb.me/JSXTransformer-0.12.0.js"></script>
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
<div id="content"></div>

JavaScript 1.7

var mountNode = document.getElementById("content");

var IncrementButton = React.createClass({
  componentWillReceiveProps : function(nextProps) {
    this.setState({
      increasing: (nextProps.val > this.props.val)
    });
  },
	render: function() {
  	return (<button onClick={this.props.handleClick}>{this.props.val}</button>);
  }
});

var Increment = React.createClass({
  getInitialState: function() {
    return {val: 0, increasing: false};
  },
  handleClick: function() {
    console.log("inHandleClick");
    console.log(this.state.val);
    this.setState({val: (this.state.val+1)});
  },
  shouldComponentUpdate: function(nextProps, nextState) {
    return (nextState.val % 5 ==0)
  },
  render: function() {
    console.log(this.state.increasing);
    return (
      <div>
      	<IncrementButton handleClick={this.handleClick} val={this.state.val}/>
      </div>
    );
  }
});

React.render(<Increment />, mountNode);