Common React PropTypes Examples

Basic

MyComp.propTypes = {
  email:     PropTypes.string.isRequired,
  seats:     PropTypes.number,
  settings:  PropTypes.object,
  callback:  PropTypes.func,
  isClosed:  PropTypes.bool,
  dataList:  PropTypes.array,
  name:      PropTypes.string,
  symbol:    PropTypes.symbol,
  any:       PropTypes.any,
};

Style and Children

What PropType should you use to check the vailidity of this.props.children and this.props.style?

MyComp.propTypes = {
  // Use this for style
  style: PropTypes.any,

  // Use this for children
  children: PropTypes.node,

  // Use this for nested children
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]),
};

Elements

MyComp.propTypes = {
  element: PropTypes.element, // react element
  node:    PropTypes.node,    // num, string, element, etc
};

Enumerables

MyComp.propTypes = {
  enum:  PropTypes.oneOf(['M','F']),  // enum
  union: PropTypes.oneOfType([        // any
    PropTypes.string,
    PropTypes.number,
  ]),
};

Arrays & Objects

MyComp.propTypes = {
  array:    PropTypes.array,
  arrayOf:  PropTypes.arrayOf(PropTypes.number),
  object:   PropTypes.object,
  objectOf: PropTypes.objectOf(PropTypes.number),
  
  // uses JavaScript's instanceof against a class
  message:  PropTypes.instanceOf(Message),

  object2:  PropTypes.shape({
    color:  PropTypes.string,
    size:   PropTypes.number,
  }),

  // like shape but will not accept extra properties
  object3:  PropTypes.exact({
    color:  PropTypes.string,
    size:   PropTypes.number.isRequired,
  }),
};

Custom

MyComp.propTypes = {
  customProp: (props, propName, componentName) => {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },
  customArrayProp: PropTypes.arrayOf(
    (propValue, key, componentName, location, propFullName) => {
    if (!/matchme/.test(propValue[key])) {
      return new Error(
        'Invalid prop `' + propFullName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  }),
}

References