React like button mount unmount
Hello React - component lifecycle - mounting and unmounting.
author(s):
Ryan Vice
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://fb.me/react-0.14.3.js"></script>
<script src="https://fb.me/react-dom-0.14.3.js"></script>
<div id="view"/>
Babel + JSX
var Button = React.createClass({
render() {
return <button onClick={this.props.onClick}>{this.props.children}</button>
}
});
var GlyphIcon = React.createClass({
render() {
return <span className={'glyphicon glyphicon-' + this.props.icon}></span>
}
});
var HelloReact = React.createClass({
getDefaultProps() {
return {likes: 0};
},
getInitialState() {
return {isIncreasing: false};
},
componentWillReceiveProps(nextProps) {
this._logPropsAndState('componentWillReceiveProps()');
console.log('nextProps.likes: ' + nextProps.likes);
this.setState({isIncreasing: nextProps.likes > this.props.likes});
},
shouldComponentUpdate(nextProps, nextState) {
this._logPropsAndState('shouldComponentUpdate()');
console.log('nextProps.likes: ' + nextProps.likes
+ ' nextState.isIncreasing: ' + nextState.isIncreasing);
return nextProps.likes > 1;
},
componentDidUpdate(prevProps, prevState) {
this._logPropsAndState('componentDidUpdate');
console.log('prevProps.likes: ' + prevProps.likes
+ ' prevState.isIncreasing:' + prevState.isIncreasing);
console.log('componentDidUpdate() gives an opportunity to execute code after react is finished updating the DOM.');
},
_logPropsAndState(callingFunction) {
console.log('=> ' + callingFunction);
console.log('this.props.likes: ' + this.props.likes);
console.log('this.state.isIncreasing: ' + this.state.isIncreasing);
},
// sets ascending value
like() {
this.setProps({likes: this.props.likes+1});
},
// sets descending value
unlike() {
this.setProps({likes: this.props.likes-1});
},
render() {
this._logPropsAndState("render()");
return (
<div>
<Button onClick={this.like}><GlyphIcon icon='thumbs-up'/> Like</Button>
<Button...