Declare Default Props and PropTypes

suggest change

There are important changes in how we use and declare default props and their types. From React 15.5, import PropTypes from the prop-types package instead of reading React.PropTypes.

React.createClass

In this version, the propTypes property is an Object in which we can declare the type for each prop. The getDefaultProps property is a function that returns an Object to create the initial props.

import React from 'react';

const MyComponent = React.createClass({
  propTypes: {
    name: React.PropTypes.string,
    position: React.PropTypes.number
  },
  getDefaultProps() {
    return {
      name: 'Home',
      position: 1
    };
  },
  render() {
    return (
      <div></div>
    );
  }
});

export default MyComponent;

React.Component

This version uses propTypes as a property on the actual MyComponent class instead of a property as part of the createClass definition Object.

The getDefaultProps has now changed to just an Object property on the class called defaultProps, as it’s no longer a “get” function, it’s just an Object. It avoids more React boilerplate, this is just plain JavaScript.

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div></div>
    );
  }
}
MyComponent.propTypes = {
  name: React.PropTypes.string,
  position: React.PropTypes.number
};
MyComponent.defaultProps = {
  name: 'Home',
  position: 1
};

export default MyComponent;

Additionally, there is another syntax for propTypes and defaultProps. This is a shortcut if your build has ES7 property initializers turned on:

import React from 'react';

class MyComponent extends React.Component {
  static propTypes = {
    name: React.PropTypes.string,
    position: React.PropTypes.number
  };
  static defaultProps = {
    name: 'Home',
    position: 1
  };
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div></div>
    );
  }
}

export default MyComponent;

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents