“You Are Not My Type” -PropTypes.
Have you ever run into issues because of passing down the wrong data type? I have. Quite recently. Luckily, PropTypes was there to save me.
Props are the backbone of passing read-only attributes from the parent component to the child component in React. Passing the wrong data type may give us headaches as we’ll need to spend time debugging why the component is behaving unexpectedly.
Though we can go for JavaScript extensions like TypeScript or Flow for type-checking, React provides a built-in library: PropTypes.
Using PropTypes, we can make sure that a component receives the type of props that it expects.
Installation
PropTypes was a utility as part of the React package, and it could be accessed with React.PropTypes before React 15.5.0.
In the newer versions of React, this utility has become a separate package called prop-types. So, we’ll need to add it to our project as a dependency like this:
npm install prop-types
Usage
We can import it from the prop-types package as follows to use it in our project:
import PropTypes from ‘prop-types’
Here is a code snippet from our function, Pagination, that we later will need:
const { itemsCount, pageSize, currentPage } = props;
We want to set the propTypes on our component. propTypes should be an object that accepts key-value pairs, where the key represents the name of the prop, and the value represents the type of prop that is available to the component.
Pagination.propTypes={
//prop type definition goes here
}
After that, we can include the variables that we have in our destructuring above in the propTypes and specify their data types:
Pagination.propTypes = {itemsCount: PropTypes.number,pageSize: PropTypes.number,currentPage: PropTypes.number};
An error will be raised in the console when an invalid prop is passed to the component:
Warning: Failed prop type: Invalid prop `currentPage` of type `string` supplied to `Pagination`, expected `number`.
isRequired
We can also chain isRequired
to the prop validator to make sure that the prop is always provided.
Pagination.propTypes = {itemsCount: PropTypes.number.isRequired,pageSize: PropTypes.number,currentPage: PropTypes.number};
If itemsCount is not passed, a warning will be displayed:
Warning: Failed prop type: The prop `itemsCount` is marked as required in `Pagination`, but its value is `undefined`.
This way, we can ensure that the data will always be passed.
defaultProps
Setting a default value is another cool feature PropTypes has. Doing that, we’ll know something gets passed even when a prop is missing:
Pagination.defaultProps = {itemsCount: 4,pageSize: PropTypes.number,currentPage: PropTypes.number};
This way, the prop itemCount will have a value no matter what.
Conclusion
We went over some of the features PropTypes has, such as isRequired, defaultProps, and some prop validators; you can visit here for detailed information.
Feel free to leave comments! 👩🏻💻