React prop type-checking: PropTypes

Igor Veyner
Nerd For Tech
Published in
2 min readAug 20, 2021

While many React applications may use TypeScript for its built in type checking if you’re working in a normal react application you can use the prop-types library to do some of the same work. Specifically this library will allow you to check that the props are the correct type and that they exist.

Installation

If you are working with React Version 16 or greater you can install the library with:

npm install — save prop-types

If you are working on an older version of React, there's no need to install, prop-types is built right into React!

Importing

To get started working with prop-types import it into a component with this line of code towards the top of your file:

import PropTypes from ‘prop-types’

If you’re working in an older version of React you can access prop-types with React.PropTypes.

Usage

The usage of prop-types will be similar to both versions. Lets start with the newer library version. First you need to define what the prop-types will be for your component by using the .propTypes method on the component like so:

Example.propTypes = {}

Inside the object is where we will declare what names and expected types of the props will be with a key value pair. To define the type we use PropTypes. and then whatever type we expect.

Example.propTypes = {  name: PropTypes.string};

For older React versions the initial setup is the same but to set the prop’s type you need to access PropTypes by doing React.PropTypes

You can accept strings, arrays, Booleans, functions, numbers, objects and a whole list of other types. For more detailed list and usage check out the official documentation.

Check for presence

To make sure a prop is always being passed along regardless of its type you can add the .isRequired method to the end of its type definition like so:

Example.propTypes = {  name: PropTypes.string.isRequired};

Case Study | Try it out !

In the example below I’ve set up a component that accepts a prop, a name, and instead of passing it a string I’ve passed it a number (oops!). The console displays a warning that there is an Invalid prop name of type number and that it expected a string instead.

Feel free to play around with this example I’ve set up. What would happen if you don’t pass in a value at all?

--

--

Igor Veyner
Nerd For Tech

Senior Software Engineer @ ASAPP | Bootcamp Grad