Validating React component properties
In React, there is a way to validate the component properties using the component's propTypes
object:
Component.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 PropTypes
object from the prop-types
package:
PropTypes.number
: This will validate whether a property is a number or notPropTypes.string
: This will validate whether a property is a string or notPropTypes.bool
: This will validate whether a property is a Boolean or notPropTypes.object
: This will validate whether a property is an object or notPropTypes.element
: This will validate whether a property is a React element or not
For a complete list of the PropTypes
validators, you can check the docs at https://facebook.github.io/react/docs/typechecking-with-proptypes.html.
By default, all...