State

Another big difference between the createClass factory and the extends React.Component method is the way you define the initial state of the components.

Again, with createClasswe use a function, while with the ES6 classes we set an attribute of the instance.

Let's see an example of that in the following code snippet:

  const Button = React.createClass({ 
getInitialState() {
return {
text: 'Click me!'
};
},
render() {
return <button>{this.state.text}</button>;
}
});

The getInitialState method expects an object with the default values for each one of the state properties.

However, with classes, we define our initial state using the state attribute of the instance and setting it inside the constructor method of the class:

  class Button extends React.Component { 
constructor(props) {
super(props);

this.state = {
text: 'Click me!'
};
}

render() {
return <button>{this.state.text}</button>;
}
}

These two ways of defining the state are equivalent but, again, with classes we just define properties on the instance without using any React-specific APIs, which is good.

In ES6, to use this in sub-classes, we first must call super. In the case of React, we also pass the props to the parent.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset