DEV Community

Cover image for What is PropTypes and how to use it in React
Cesare Ferrari
Cesare Ferrari

Posted on • Updated on

React Proptypes 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
Enter fullscreen mode Exit fullscreen mode

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

import PropTypes from 'prop-types';
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (3)

Collapse
 
prafulla-codes profile image
Prafulla Raichurkar

Thanks !

Collapse
 
imshubh7 profile image
Shubham Chaudhari

Thanks for the details

Collapse
 
yukimyona profile image
Oluwapelumi Odumosu

Thanks for this. I saw it somewhere and this helped me understand what it does. Thanks again, if definitely start using it 😇