How do you validate the PropTypes of a nested object in ReactJS?

You can use React.PropTypes.shape to validate properties:

propTypes: {
    data: React.PropTypes.shape({
      id: React.PropTypes.number.isRequired,
      title: React.PropTypes.string
    })
}

Update

As @Chris pointed out in comments, as of React version 15.5.0 React.PropTypes has moved to package prop-types.

import PropTypes from 'prop-types';    

propTypes: {
    data: PropTypes.shape({
      id: PropTypes.number.isRequired,
      title: PropTypes.string
    })
}

More info


Wanted to note that nesting works beyond one level deep. This was useful for me when validating URL params:

propTypes = {
  match: PropTypes.shape({
    params: PropTypes.shape({
      id: PropTypes.string.isRequired
    })
  })
};

If React.PropTypes.shape doesn't give you the level of type checking you want, have a look at tcomb-react.

It provides a toPropTypes() function which lets you validate a schema defined with the tcomb library by making use of React's support for defining custom propTypes validators, running validations using tcomb-validation.

Basic example from its docs:

// define the component props
var MyProps = struct({
  foo: Num,
  bar: subtype(Str, function (s) { return s.length <= 3; }, 'Bar')
});

// a simple component
var MyComponent = React.createClass({

  propTypes: toPropTypes(MyProps), // <--- !

  render: function () {
    return (
      <div>
        <div>Foo is: {this.props.foo}</div>
        <div>Bar is: {this.props.bar}</div>
      </div>
    );
  }    
});

Tags:

Reactjs