What is PropTypes and how to use it in React

PropTypes makes sure the props objects pass the correct types to a component

Javascript is not a strongly typed language. Javascript functions are happy to accept data of different types than what we expected when we declared the function.
For example, we can pass a number to a function that expects a string. What Javascript will do is try to convert the number into a string and go on to the next operation.

This may be what we want, but it may also lead to bugs and errors in the code when the operations performed on a piece of data are not what we thought we were doing because the data passed in is of a different type.

PropTypes is a library that helps in minimizing this problem in React by checking the types passed in the props object against a specification we set beforehand and to raise a warning if the types passed don't match the types expected.
To use PropTypes we need to install the library with this command:

npm install --save prop-types

Then we import the library at the top of the component where we want to use it, like so:

import PropTypes from 'prop-types';

Next, we call the propTypes property on our component and pass it an object that specifies the props object expected types.

For example, we may have a Pokemons component that is passed an array of pokemons objects. Since we know that pokemons must be an array, we can use PropTypes to enforce this type.
At the bottom of our component file, we add this code:

Pokemons.propTypes = {
  pokemons: PropTypes.array
}

Now if we passed pokemons as a different type, a string or an object for example, we would get a warning in the Javascript console in our browser.
To learn more about PropTypes you can check out the documentation here: Typechecking With PropTypes.

If you like this article and want to receive more in your inbox, just click the button below to sign up for a free subscription.