Validating React component properties

In React, there is a way to validate the component properties using the component's propTypes object:

propTypes: {
  propertyName: validator
}

In this object, you need to specify a property name and a validator function that will determine whether a property is valid or not. React provides some predefined validators for you to reuse. They are all available in the React.PropTypes object:

  • React.PropTypes.number: This will validate whether a property is a number or not
  • React.PropTypes.string: This will validate whether a property is a string or not
  • React.PropTypes.bool: This will validate whether a property is a Boolean or not
  • React.PropTypes.object: This will validate whether a property is an object or not
  • React.PropTypes.element ...

Get React: Building Modern Web Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.