In many examples I've see to manage state inside of a react component you will have to use getInitialState such as in this example.
var LikeButton = React.createClass({
getInitialState: function() {
return {liked: false};
},
handleClick: function(event) {
this.setState({liked: !this.state.liked});
},
render: function() {
var text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.
</p>
);
}
});
But in ES6 syntax using getInitalState() will not work anymore. So how so you manage state in a react component using ES6 syntax?
An example is
// Future Version
export class Counter extends React.Component {
static propTypes = { initialCount: React.PropTypes.number };
static defaultProps = { initialCount: 0 };
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>
);
}
}
Thanks
in ES6, The React team decided a more idiomatic way of initializing state was simply to store it in an instance variable setup in the constructor. This means you can refactor away your getInitialState
method by moving its return value to be assigned to the this.state
instance variable in your class' constructor.
import React, { Component } from 'react';
class LikeButton extends Component {
constructor() {
super();
this.state = { liked : false };
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({
liked : !this.state.liked
});
}
render() {
const text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>{`You ${text} this. Click to toggle.`}</p>
);
}
}
NOTE: you must bound your methods to a component instance
in ES6+ you can use Property initializers feature
import React, { Component } from 'react';
class LikeButton extends Component {
state = {
liked : false
}
render() {
const text = this.state.liked ? 'like' : 'haven\'t liked';
const handleClick = ()=>{
this.setState({
liked : !this.state.liked
});
}
return (
<p onClick={this.handleClick}>{`You ${text} this. Click to toggle.`}</p>
);
}
}
NOTE: This is a Stage 0 proposal.
NOTE: i dropped the constructor
so defined handleClick
as nested function inside render
Refrences: React official docs / Article
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With