Type Checking using PropTypes in React

Tanuka Das
JavaScript in Plain English
4 min readNov 10, 2020

--

PropTyping allows us to bring type checking to props, so this is the data passed down from the parent component to the child component. This makes debugging our react application much easier. For the purpose of this article, I will a simple book application as an example.

by Markus Spiske

How does it work?

To get started, create a simple react app and install the proptypes package, npm install --save prop-types. Now if you check the package.json file you should have an entry of prop types. Next, import proptypes into our component file.

import React, { Component } from 'react';
import PropTypes from "prop-types"
class BookDetail extends React.Component {
render() {
return (
<h1>{this.props.book}</h1>
);
}
}

Here is the book data we will use as an example.

export const storeProducts = [
{
id: 5,
title: "Behold the Dreamers (Oprah's Book Club)",
img: "img/BeholdtheDreamers-5.png",
price: 24,
author: "Imbolo Mbue",
info:
"Jende Jonga, a Cameroonian immigrant living in Harlem, has come to the United States to provide a better life for himself, his wife, Neni, and their six-year-old son. In the fall of 2007, Jende can hardly believe his luck when he lands a job as a chauffeur for Clark Edwards, a senior executive at Lehman Brothers. Clark demands punctuality, discretion, and loyalty—and Jende is eager to please. Clark’s wife, Cindy, even offers Neni temporary work at the Edwardses’ summer home in the Hamptons. With these opportunities, Jende and Neni can at last gain a foothold in America and imagine a brighter future...",
inCart: false,
count: 0,
total: 0
}
]

Now explore the possibility that there is something wrong with the data. Let’s say you, somebody in the team, or somebody who was working on the project previously messes up the API by assigning the price to a boolean value and the inCart to an integer. These can cause us tons of bugs in our application.

export const storeProducts = [
{
id: 5,
title: "Behold the Dreamers (Oprah's Book Club)",
img: "img/BeholdtheDreamers-5.png",
price: true,
author: "Imbolo Mbue",
info:
"Jende Jonga, a Cameroonian immigrant living in Harlem, has come to the United States to provide a better life for himself, his wife, Neni, and their six-year-old son. In the fall of 2007, Jende can hardly believe his luck when he lands a job as a chauffeur for Clark Edwards, a senior executive at Lehman Brothers. Clark demands punctuality, discretion, and loyalty—and Jende is eager to please. Clark’s wife, Cindy, even offers Neni temporary work at the Edwardses’ summer home in the Hamptons. With these opportunities, Jende and Neni can at last gain a foothold in America and imagine a brighter future...",
inCart: "24",
count: 0,
total: 0
}
]

This is where typechecking comes in. We have a BookDetail component, which is our child component. We want to type check the props that are being sent from the parent component to our child component. First, we will attach a special property to BookDetail. Call propTypes on the name of the component and set it equal to an object. From here we can assign what we need to validate. In this case, we’ve book as our prop, using the shape method to allow objects to take a particular shape. Within the shape method, we will assign what we expect our object properties to be, which are id, img, title, price, and inCart.

class BookDetail extends React.Component {
render() {
return (
<h1>{this.props.book}</h1>
);
}
}
// Typechecking using PropType
BookDetail.propTypes = {
book: PropTypes.shape({
//here the PropType is looking for a number
id: PropTypes.number,
//the PropType is looking for an string
img: PropTypes.string,
title: PropTypes.string,
price: PropTypes.number,
//here the PropType is looking for a boolean
inCart: PropTypes.bool
}).isRequired
}

After applying the shape method now that we set up the PropTypes, the next step is to make this required. As you save this, you will receive the following error on your console.

Warning: Failed prop type: Invalid prop `book.price` of type `boolean` supplied to `BookDetail`, expected `number`.
in BookDetail (at BookList.js:24)
in div (at BookList.js:20)
in div (at BookList.js:17)
in div (at BookList.js:16)
in BookList (created by Context.Consumer)
in Router (created by BrowserRouter)
in BrowserRouter (at src/index.js:11)
in BookProvider (at src/index.js:10)

The error clearly indicates that the book type is current a boolean, but it is expecting a number. Now you can go back to your data and check where the changes are required. In this case, we will change the price to an integer value. Next, it will throw an error for the inCart value, which is currently a string, and we change that to a boolean.

TypeChecking with prop-types is a quick and easy way to check if you’ve any errors in your data or if it’s running properly. Definitely give this a try on your next project.

--

--