PropTypes
Learn how to ensure that the data we receive in our components is of the correct type by using typechecking in both class and function components.
PropTypes have a long-standing history in React and were part of React before it even gained popularity. In React version 15.5, PropTypes were removed from the core of React and converted into their own prop-types
package. Even though we defined PropTypes via React.PropTypes.string
in the past, we’ll now access them via importing the PropTypes
module and PropTypes.string
.
This change also means that we now have to install the PropTypes
module as a
devDependency. We can execute the following step in the command line:
npm install --save-dev prop-types
Or, if we want to use Yarn:
yarn add --dev prop-types
PropTypes can be seen as a kind of interface that defines which types the props can take, and whether they are required or optional. If PropTypes encounter discrepancies, React will inform us of these as long as we are in development mode. When applications have been built correctly and use either the production build of React or an environment variable process.env.NODE_ENV=production
, this warning will not be shown anymore.
But how do PropTypes work? To answer this question, we must differentiate between class components and function components.
PropTypes in Class components
Class components implement PropTypes as a static property of the component in question:
Get hands-on with 1200+ tech skills courses.