PropTypes
Every React app will be composed of an hierarchical tree of components that have different props, certainly then we will need to define and structure our props , to avoid bugs and errors .
Just as a function may have required arguments, a React component may require a prop to be defined in order to render properly. If you fail to pass a required prop into a component that requires it, your app may behave unexpectedly.
Lets take the example below
This alert component requires four props for proper rendering: title
,importantMessage
,riskNumber
, and total
. Default values are set for total
prop in case they are not provided.
Based on what we see we can conclude that title
and importantMessage
props are expected to be a string
. In the same vein, riskNumber
and total
are required to be numeric
values because they are used for computing percent
. Also, total
is expected to never be 0
since it is being used as a divisor.
But what if we define the props with wrong types like this
The app will render with invalid props, try to imagine this problem in a big complex app , that's why we needed to find a solution to define props type and keep the sanity of the developers
Proptypes
PropTypes is React’s internal mechanism for adding type checking to components.
React components use a special property named propTypes
to set up type checking.
When props are passed to a React component, they are checked against the type definitions configured in the propTypes
property. When an invalid value is passed for a prop, a warning is displayed on the JavaScript console.
So how can i create a prototype validation for Alert component props .let's take a look at the code below :
Alert.propTypes
it's an object that react reference when it render a component with props and pass each one of them to a validation function that we provide
Her we have validated the title prop to be always of type string
And here you go a custom error for in our console to alert us of prop validation problems
we can even push it forward by creating an object that define generic validation like defining a generic error for every prop that need to be string or number:
Proptypes doesn't chip with production build for performance issues , as it's a tool for developer to maintain and structure the code , it's not necessarily to have it on production either way
Prop-types package
It will always be nicer if we had pre built validators for our props , as it will be a little bit tedious to define prop types over and over again, and here come prop-type package
Prior to React 15.5.0, a utility named PropTypes
was available as part of the React package, which provided a lot of validators for configuring type definitions for component props. It could be accessed with React.PropTypes
.
However, in later versions of React, this utility has been moved to a separate package named prop-types
, so you need to add it as a dependency for your project in order to get access to the PropTypes
utility.
It can be imported into your project files as follows:
To learn more about how you can use prop-types
, how it differs from using React.PropTypes
, and all the available validators, see the official prop-types
documentation.
React PropTypes validators
The PropTypes utility exports a wide range of validators for configuring type definitions. Below we’ll list the available validators for basic, renderable, instance, multiple, collection, and required prop types.
Basic types
Below are the validators for the basic data types.
PropTypes.any
: The prop can be of any data typePropTypes.bool
: The prop should be a BooleanPropTypes.number
: The prop should be a numberPropTypes.string
: The prop should be a stringPropTypes.func
: The prop should be a functionPropTypes.array
: The prop should be an arrayPropTypes.object
: The prop should be an objectPropTypes.symbol
: The prop should be a symbol
Renderable types
PropTypes
also exports the following validators for ensuring that the value passed to a prop can be rendered by React.
PropTypes.node
: The prop should be anything that can be rendered by React — a number, string, element, or array (or fragment) containing these typesPropTypes.element
: The prop should be a React element
One common usage of the PropTypes.element
validator is in ensuring that a component has a single child. If the component has no children or multiple children, a warning is displayed on the JavaScript console.
Instance types
In cases where you require a prop to be an instance of a particular JavaScript class, you can use the PropTypes.instanceOf
validator. This leverages the underlying JavaScript instanceof
operator.
Multiple types
PropTypes
also exports validators that can allow a limited set of values or multiple sets of data types for a prop. Here they are:
PropTypes.oneOf
: The prop is limited to a specified set of values, treating it like an enumPropTypes.oneOfType
: The prop should be one of a specified set of types, behaving like a union of types
Collection types
Besides thePropTypes.array
and PropTypes.object
validators, PropTypes
also provides validators for more fine-tuned validation of arrays and objects.
PropTypes.arrayOf
PropTypes.arrayOf
ensures that the prop is an array in which all items match the specified type.
PropTypes.objectOf
PropTypes.objectOf
ensures that the prop is an object in which all property values match the specified type.
PropTypes.shape
You can use PropTypes.shape
when a more detailed validation of an object prop is required. It ensures that the prop is an object that contains a set of specified keys with values of the specified types.
PropTypes.exact
For strict (or exact) object matching, you can use PropTypes.exact
as follows:
Required types
The PropTypes
validators we’ve explored so far all allow the prop to be optional. However, you can chain isRequired
to any prop validator to ensure that a warning is shown whenever the prop is not provided.
Custom validators for type-checking React props
Usually, you need to define some custom validation logic for component props — e.g., ensuring that a prop is passed a valid email address. prop-types
allows you to define custom validation functions that can be used for type checking props.
Basic custom validators
The custom validation function takes three arguments:
props
, an object containing all the props passed to the componentpropName
, the name of the prop to be validatedcomponentName
, the name of the component
If the validation fails, it should return an Error
object. The error should not be thrown. Also, console.warn
should not be used inside the custom validation function.
Custom validation functions can also be used with PropTypes.oneOfType
. Here is a simple example using the isEmail
custom validation function in the previous code snippet:
Component
will be valid in both of these scenarios:
Custom validators and collections
Custom validation functions can also be used with PropTypes.arrayOf
and PropTypes.objectOf
. When used this way, the custom validation function are called for each key in the array or object.
However, the custom validation function takes five arguments instead of three:
propValue
, the array or object itselfkey
, the key of the current item in the iterationcomponentName
, the name of the componentlocation
, the location of the validated data (usually“prop”
)propFullName
, the fully resolved name of the current item being validated. For an array, this will bearray[index]
; for an object, it will beobject.key
Below is a modified version of the isEmail
custom validation function for use with collection types.
All-purpose custom validators
Taking all we’ve learned about custom validation functions into account, let’s go ahead and create all-purpose custom validators that can be used as standalone validators and also with collection types.
A slight modification to the isEmail
custom validation function will make it an all-purpose validator, as shown below.
I intensively use Typescript for all what concerns Types and types checking , and with that and i don't ever use proptypes in my projects , but it's always good to have such an amazing features on your grasp
Last updated