Props

The first difference is in how we can define the props that a component expects to receive, and the default values for each one of the props.

We will see how props work in detail further into this chapter, so let's now concentrate on how we can define them.

With createClass, we declare the props inside the object that we pass as a parameter to the function, and we use the getDefaultProps function to return the default values:

  const Button = React.createClass({ 
propTypes: {
text: React.PropTypes.string
},
getDefaultProps() {
return {
text: 'Click me!'
};
},
render() {
return <button>{this.props.text}</button>;
}
});

As you can see, we use the propTypes attribute to list all the props that we can pass to the component.

We then use the getDefaultProps function to define the values that the props are going to have by default, and which will be overwritten by the props passed from the parent, if they are present.

To achieve the same result using classes, we have to use a slightly different structure:

  class Button extends React.Component { 
render() {
return <button>{this.props.text}</button>;
}
}

Button.propTypes = {
text: React.PropTypes.string
};

Button.defaultProps = {
text: 'Click me!'
};

Since class properties are still in draft (they are not part of the ECMAScript standard yet), to define the properties of the class we have to set the attributes on the class itself, after it has been created.

As you can see in the example, the propTypes object is the same we used with createClass.

When it comes to setting the default props instead, we used to use a function to return the default properties object; but with classes, we have to define a defaultProps attribute on the class and assign the default props to it.

The good thing about using classes is that we define properties on the JavaScript object without having to use React-specific functions, such as getDefaultProps.

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

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