PropTypes

suggest change

propTypes lets you specify which props your component needs and what type they should be. Your component will work without propTypes, but defining them makes the component more readable, documents it for other developers, and, during development, makes React warn you if you set a prop whose type does not match the definition.

As of React 15.5, PropTypes lives in the separate prop-types package rather than on React.PropTypes.


Some primitive and commonly used propTypes are:

optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalSymbol: React.PropTypes.symbol

If you attach isRequired to any prop type, that prop must be supplied when the element is created. If you omit a required prop, React still creates the component, but in development it logs a warning. The production build does not.

Syntax

ES5

var MyClass = React.createClass({
  propTypes: {
    randomObject: React.PropTypes.object,
    callback: React.PropTypes.func.isRequired
    // ...
  }
});

ES6

class MyClass extends React.Component {}

MyClass.propTypes = {
  randomObject: React.PropTypes.object,
  callback: React.PropTypes.func.isRequired
  // ...
};

ES7

class MyClass extends React.Component {
    static propTypes = {
        randomObject: React.PropTypes.object,
        callback: React.PropTypes.func.isRequired
        // ...
    };
}

More complex prop validation

In the same way, PropTypes lets you specify more complex validation.

Validating an object

...
    randomObject: React.PropTypes.shape({
        id: React.PropTypes.number.isRequired,
        text: React.PropTypes.string,
    }).isRequired,
...

Validating an array of objects

...
    arrayOfObjects: React.PropTypes.arrayOf(React.PropTypes.shape({
        id: React.PropTypes.number.isRequired,
        text: React.PropTypes.string,
    })).isRequired,
...

Feedback about page:

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



Table Of Contents