OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

How to forget about type errors in your React props with PropTypes

Nwose Lotanna Victor
February 25th, 2021 · 5 min read

Do you write or maintain code using React? Then you must be familiar with constant debugging that happens as you build and after you build an app. Do you want to reduce debug time drastically, then this post is for you. In this article, we will be looking at how to making your debugging process faster with prop types in React, what they are, how they are related to TypeScript, and how they are used with practical examples.

What are prop types

React prop type is a library supported by React that lets you define types for props in your components. Prototypes are a simple way of validating or ensuring that the data we pass from one component to another or from one element to another is the exact type of data we intend on passing. In React, one of the ways to pass data is through properties and so as you will see later in this post, it is important to check those types. Since React is a JavaScript framework and we know that it is dynamically typed, so property types in JavaScript are determined at runtime. Type checking is something TypeScript as a language is well known for and so you might wonder how they relate with React prop types.

As your application gets bigger and bigger the chances of having more bugs increase, knowing that you can catch a lot of them easily through type-checking is a great thing. With Proptypes, whether or not you are writing, reading, or maintaining a codebase the components will always be predictable for you.

How it relates to TypeScript

TypeScript is a statically typed version of JavaScript which solves the dynamic typing issues around knowing or enforcing types for not just properties but for almost everything else in JavaScript. However, with TypeScript, the types are checked at compile time which means that as you write your code you get the warnings in real-time. With Proptypes, these checks happen at runtime and so are focused on component interaction and debugging. Using prop types in React gives you a bit of the TypeScript experience at runtime without having to use TypeScript.

The problem

The interesting use case here is how you can pass in any type of data and it compiles without any warnings in React. This can be very costly as it becomes tough to notice while debugging and most of the time these are the kinds of things that the user of the application first notices.

What we will be building

How does your component look without prop types? Let us find out with this demo below

demo gif

This is a simple car list displayed in a card-like form, if you followed this post from the start you must have created the “propstest” project which we will be using throughout this tutorial. Navigate to a folder of your choice and open that in VS Code, run the command below in the terminal:

1npx create-react-app propstest

Inside the source folder create a components folder and then a functional component file, call it Car.js and copy this code block below inside it:

1import React from "react"
2const Car = (prop) => {
3 return ( <div className = "container responsive" >
4 <div className = "car" >
5 <h2 > This {prop.brand} {prop.model
6 } < /h2>
7 <h4 > has a millage of {prop.milage} < /h4>
8 <h4 > It is an electric vehicle - {prop.isElectric} < /h4>
9 <ul > {
10 prop.owners.map((owner, key) => {
11 return <li key = {key} > {owner} < /li>;
12 })
13 }
14 </ul>
15 </div>
16 </div>
17 );
18};
19export default Car;

This is a simple functional component that renders and export Car template with some headers and a list. Inside the source folder, you can see the app component (App.js) file, copy the code block below into the app.js file:

1import './App.css';
2import Car from './Components/Car'
3
4function App() {
5 return ( <div className = "App" >
6 <Car brand = "Tesla"
7 model = "CyberTruck"
8 milage = {5000}
9 isElectric = {"true"}
10 owners = {["Lotanna"]}
11 />
12 <Car brand = "Ford"
13 model = "Explorer"
14 milage = {8000}
15 isElectric = {"false"}
16 owners = {["Runor", "Elijah"]}
17 />
18 <Car brand = "Benz"
19 model = "CLA250"
20 milage = {7500}
21 isElectric = {"false"}
22 owners = {["Gilbert", "Herbert", "Frank", "Mazior"]}
23 />
24 <Car brand = "Toyota"
25 model = "Camry"
26 milage = {3000}
27 isElectric = {"false"}
28 owners = {["Ebuka", "Ikenna", "Ekene"]}
29 />
30 </div >
31 );
32}
33export default App;

Here we are bringing in the defined templates and telling React to render it four times with our own pre-defined properties. These properties include the car brand, the model, mileage, and the owners of the car. When you run the dev server command:

1npm start

You will see information all scattered, adding a little CSS rule to make it look presentable, navigate to the app.css file and copy these styles below:

1.App {
2 text-align: center;
3}
4
5.container {
6 position: relative;
7}
8
9ul {
10 list-style-type: none;
11 text-align: center;
12}
13
14.car {
15 top: 50%;
16 text-align: center;
17 border-radius: 25px;
18 border: 2px solid #73AD21;
19 padding: 20px;
20 width: 600px;
21 height: 250px;
22 margin-left: 25%;
23 margin-bottom: 15px;
24}

Running the dev server command again, you will notice in your browser at http: //localhost:3000/ that it looks exactly like the demo gif we have above. Now we can go into the app component file and change the Tesla string to a number, say 5000 and the milage to Rabbit, the application still runs fine without an error or warning at all. null

Things like this can be very hard to catch during a debugging session, it can happen through human error, direct user input or data from another component or API especially if you are not the author of the codebase. We can go even further to change the owner’s side from an array containing “lotanna” to just a string.

null

The app crashes on compile, but not because of the type, only because we have a map function for the owners, and the map only works on a list (in our case, an array) ## Solution: prop types A great solution to this problem is to define the types for every prop you want to use. The Syntax of prop types looks like this in a functional component:

1import PropTypes from 'prop-types'
2
3function HelloWorldComponent( {name}) {
4 return (<div>Hello, {name} </div>)
5}
6
7HelloWorldComponent.propTypes = {
8 name: PropTypes.string
9}
10
11export default HelloWorldComponent

Let us see how it works in our app, start by installing the prop types package inside your project with this command:

1npm install proptypes

Inside the component you want to define the types, import the installed prop types, in our case inside the Car.js file:

1import React from "react"
2import PropTypes from "prop-types"
3const Car = (prop) => {
4 return ( <
5 div className = "container responsive" >
6 <div className = "car" >
7 <h2> This {prop.brand } { prop.model } < /h2>
8 <h4> has a millage of { prop.milage } < /h4>
9 <h4 > It is an electric vehicle - { prop.isElectric } </h4>
10 <ul> {
11 prop.owners.map((owner, key) => {
12 return <li key = {key} > {owner} < /li>;
13 })
14 }
15 </ul>
16 </div>
17 </div>
18 );
19};
20Car.propTypes = {
21 brand: PropTypes.string,
22 model: PropTypes.string,
23 milage: PropTypes.number,
24 isElectric: PropTypes.string,
25 owners: PropTypes.arrayOf(PropTypes.node)
26}
27export default Car;

Notice the prop types being defined before the export of the component, that is very important because if you export before defining the prop types, it would not work in the dev server.

This reminds me so much of form validator libraries, they are basically structured like this as well. We added a few prop types in this Car component and some of them are:

  • Proptype.string: This defines the type of prop required here is of type string.
  • Proptype.number: This defines the needed type of prop here to be type number.
  • Proptype.arrayOf: This defines the type of prop required here to be an array type, inside which you can now specify exactly the type of the children.
  • Proptype.node: This defines the type of anything that can be rendered in the UI. That includes numbers, strings, elements, an array, or even fragments.

There are other types you can read about in the documentation here.

Testing the prop types

Now if you run the application in your dev server you will see that everything runs perfectly however when you try to change Tesla to a number the application still runs but this time it shows a warning in the console.

null

These warnings are very descriptive that once you read them you know exactly what has gone wrong and what to fix.

More use cases: OneOf example

It gets even more interesting, with oneOf you can specify the exact value you want from your props so no matter where the data source is, if it does not match your specifications you would get the warning. Let us define exact values in the Car component like this:

1import React from "react"
2import PropTypes from "prop-types"
3const Car = (prop) => {
4 return ( <div className = "container responsive" >
5 <div className = "car" >
6 <h2 > This { prop.brand } { prop.model } < /h2>
7 <h4 > has a millage of { prop.milage } < /h4>
8 <h4 > It is an electric vehicle - { prop.isElectric } < /h4>
9 <ul> { prop.owners.map((owner, key) => {
10 return <li key = { key } > { owner } < /li>;
11 })
12 }
13 </ul>
14 </div>
15 </div>
16 );
17};
18Car.propTypes = {
19 brand: PropTypes.oneOf(['Ford', 'Benz', 'Toyota']),
20 model: PropTypes.string,
21 milage: PropTypes.number,
22 isElectric: PropTypes.string,
23 owners: PropTypes.arrayOf(PropTypes.node)
24}
25export default Car;

You can see we specified the exact values we needed and I purposely omitted Tesla and so when we run the app again, here is the warning we get.

null

Prop types in class components

Prop types also work well in React class components, let us quickly create one class component. Open the components folder and create a new component file, call it Sample.js , and inside it copy the code block below:

1import React from "react"
2import PropTypes from 'prop-types';
3class Greeting extends React.Component {
4 render() {
5 return ( <h1 > Hello, { this.props.brand } < /h1>
6 );
7 }
8}
9Greeting.propTypes = {
10 brand: PropTypes.string
11};
12export default Greeting;

Inside the app component file (App.js) import Greeting and add the corresponding template like this:

1import './App.css';
2import Car from './Components/Car'
3import Greeting from './Components/Sample'
4
5function App() {
6 return ( <
7 div className = "App" >
8 <Greeting brand = "Reader" />
9 <Car brand = { 4555 }
10 model = "CyberTruck"
11 milage = { 5000 }
12 isElectric = { "true" }
13 owners = { ["Lotanna"] }
14 />
15 <Car brand = "Ford"
16 model = "Explorer"
17 milage = { 8000 }
18 isElectric = { "false" }
19 owners = { ["Runor", "Elijah", 3] }
20 />
21 <Car brand = "Benz"
22 model = "CLA250"
23 milage = {7500}
24 isElectric = { "false" }
25 owners = { ["Gilbert", "Herbert", "Frank", "Mazior"] }
26 />
27 <Car brand = "Toyota"
28 model = "Camry"
29 milage = { 3000 }
30 isElectric = { "false" }
31 owners = { ["Ebuka", "Ikenna", "Ekene"] }
32 />
33 < /div >
34 );
35}
36export default App;

When you run it in the dev server you can see it shows up like this:

null

Observability for Production React Apps

Debugging React apps in production may be challenging and time consuming. OpenReplay is an open-source session replay stack for developers. It helps you replay everything your users do and shows how your app behaves and renders for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder.

OpenReplay Frontend Monitoring

OpenReplay helps to quickly get to the root cause by reproducing issues as if they happened in your own browser. It also monitors your frontend performance by capturing key metrics such as page load time, memory consumption and slow network requests as well as Redux actions/state.

Happy debugging, for modern frontend teams - Start monitoring your web app for free.

Wrapping up

In this tutorial, we have taken a look at prop types in React, why they are important and how they can be relatable to TypeScript. We also took a look at how they are used with various examples and a working demo. I hope you would adopt prop types going forward to make debugging and maintaining your code easier. Happy hacking!

More articles from OpenReplay Blog

Server Side Rendering (SSR) with React

Learn how easy it is to do Server Side Rendering with React and NextJS

February 25th, 2021 · 5 min read

6 React Best Practices For 2021

6 tips for writing better React in 2021

February 10th, 2021 · 5 min read
© 2021 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552