React ES5 to ES6: props and state

Developing with React and ES5, state on a Component is configured using the getInitialState() function:

var ButtonComponent = React.createClass({

  getInitialState : function(){
    return({
      value1: this.props.value1,
      value2: this.props.value2
    });
 },

...

});

If you’re moving from ES5 TO ES6 and creating React components using ES6 classes, if you try to follow the same approach you’ll see an error like this:

To set the initial state on an ES6 React class, you establish it in the constructor like this:

constructor(props) {
  super(props);
  this.state = {
    value1 : this.props.value1,
    value2 : this.props.value2,
  };
 }

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.