Last active
December 18, 2015 16:48
-
-
Save biglovisa/8720e358ef234aa4dbe9 to your computer and use it in GitHub Desktop.
Old vs New React class syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Older | |
///////////// Here, we specify the defaultProps and the initialState in functions in the component | |
///////////// We also validate the component props in the propTypes function | |
var Counter = React.createClass({ | |
getDefaultProps: function(){ | |
return {initialCount: 0}; | |
}, | |
getInitialState: function() { | |
return {count: this.props.initialCount} | |
}, | |
propTypes: {initialCount: React.PropTypes.number}, | |
tick() { | |
this.setState({count: this.state.count + 1}); | |
}, | |
render() { | |
return ( | |
<div onClick={this.tick}> | |
Clicks: {this.state.count} | |
</div> | |
); | |
} | |
}); | |
/// Newer | |
//////////// Here, default props and propTypes are declared inside the component. | |
//////////// We set the initial state in a constructor function. State should be declared in the defaultProps object. | |
//////////// Note: methods are no longer implicitly bound to the component, so you need to use bind/arrow syntax | |
class Counter extends React.Component { | |
static propTypes = {initialCount: React.PropTypes.number}; | |
static defaultProps = {initialCount: 0}; | |
constructor(props) { | |
super(props); | |
this.state = {count: props.initialCount}; | |
} | |
state = {count: this.props.initialCount}; | |
tick() { | |
this.setState({count: this.state.count + 1}); | |
} | |
render() { | |
return ( | |
<div onClick={this.tick.bind(this)}> | |
Clicks: {this.state.count} | |
</div> | |
); | |
} | |
} | |
/// Newer (also works) | |
//////////// We declare the state in the constructor function | |
//////////// Proptypes and default props are set outside of the component. | |
//////////// Note: methods are no longer implicitly bound to the component, so you need to use bind/arrow syntax | |
export class Counter extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = {count: props.initialCount}; | |
} | |
tick() { | |
this.setState({count: this.state.count + 1}); | |
} | |
render() { | |
return ( | |
<div onClick={this.tick.bind(this)}> | |
Clicks: {this.state.count} | |
</div> | |
); | |
} | |
} | |
Counter.propTypes = { initialCount: React.PropTypes.number }; | |
Counter.defaultProps = { initialCount: 0 }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment