What is PropTypes in React

Anastasia Orlova
Dev Genius
Published in
2 min readDec 28, 2020

--

Recently, while working my way through this tutorial, I came across a React library called prop-types. I’ve never used this library before, so I made a quick research on why we need prop-types and how to use is.

JavaScript is a so-called “untyped” language. That means JavaScript will figure out what type of data you have and make a function work without any required adjustments. For example, it can convert a number into a string if it is what a function expects. Sound great, right? However, it can be a blessing until it turns into a curse.

As your app grows, this JavaScript feature can lead to bugs and errors when the data type we expected is not the one we’ve passed. So, to check that data type seems like a smart decision. That’s where React built-in type checking ability comes into play. PropTypes is a library that helps to check whether the props you pass have the type you’re waiting for.

Anyway, our first step is to install the library.

npm install — save prop-types

The second step is to import the library.

import PropTypes from 'prop-types';

Our third and last step is to assign special propTypes property. This library offers a great range of validators that can be used to make sure the data you receive is valid. All we need to do is to call the propTypes property on our component and specify the data type.

Here is what I have for my recent project. I have a Question component whose prop.content supposed to be a string. Now, if I pass an object of a different type, I’ll get a warning. Also, I added .isRequired to make sure a warning is shown if the props isn't provided.

Hope you find this short blog helpful!

Source:

  1. What is PropTypes
  2. React documentation
  3. Mastering Props And PropTypes In React

--

--