React Proptypes

Master React PropTypes With This Comprehensive Guide

July 15, 2022
Harita Ravindranath
React.js

The Fastest Way to Build React UI

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Introduction

In React, we build applications by breaking down the UI into several components. Often, we use React props to pass data from one React component to another. React props allows us to pass different type of data between two components like string, number, array, object, or even function. 

But what happens if you forget to pass a required prop to the component or the component receives the wrong type of props? The React component will not render properly leading to bugs and unexpected behavior in your app. Hence, it is always a good practice to type-check the data we get as props, especially as the app grows larger and more complex. Type-checking also aids in debugging and avoiding any bugs in the future.

As JavaScript doesn’t have an in-built type-checking solution, many developers use extensions like Flow or TypeScript to type-check the whole app. However, React offers you some in-built prop validation mechanism called as PropTypes. In this comprehensive guide, let us learn what is React PropTypes, how to integrate PropTypes with React, and how to use PropTypes effectively in your app with lots of examples. 


Let’s start!

What are Props in React?

Before getting started with PropTypes, let us briefly talk about the concept of Props in React. You may also refer this video tutorial which explains React props in detail.

Props (short for “properties”) is a React mechanism for passing read-only attributes between React components. Props are mainly used to share data from parent to child components, though the reverse is also possible. Using Props, you can share different types of data including 

  • String
  • Number
  • Boolean
  • Array
  • Object
  • Function, etc.

To pass props between components, all you need to do is add them as attributes when the React component is called like we declare attributes for any HTML tag. Let us see an example of how to pass and access data using Props.

Here, we have the parent component, UserList, from which we are calling the child component, User, and passing the props name, age and occupation.

import React from "react";
import User from './User';
 
const UserList = () => {
  return (
    <div>
      <h3>User List</h3>
      <User
        name="John"
        age={25}
        occupation="Web Developer"
      />
      <User
        name="Jane"
        age={28}
        occupation="UI/UX Designer"
      />
    </div>
  );
};
 
export default UserList;

From the child component (from parent component), we can access the properties described in the component call from the props object.

import React from "react";
 
const User = (props) => {
  const { name, age, occupation } = props;
 
  return (
    <div>
      My name is {name}. I am {age} years old. I am a {occupation}
    </div>
  );
};
 
export default User;

What are PropTypes in React?

React PropTypes is a mechanism that adds type-checking to the props of the React applications’ components. Prop types ensure that the data of the correct type passes and receives in the components. We can configure the type definitions for each prop, and whenever a prop is passed to React components, it will be type-checked against its type definition. Whenever an invalid type value is passed, a warning pops up on the JavaScript console, which needs to be resolved. So check your JavaScript console frequently!

When do Proptypes get checked in React?

When it comes to debugging your app, Prop Types are a good first line of defense. If set, even the default prop values for the component are subject to the prop type definitions. It is worth noting that the Prop type checking happens only during the runtime in the development mode of the React application to catch bugs. In production mode, prop types are disabled for performance reasons.

How to use PropTypes in React?

To make use of PropTypes in our React application, we need to add a package dependency named prop-types.In this section, let us learn how to install and use PropTypes in your React application.

Why did React get rid of PropTypes? 

Prior to the release of v15.5, PropTypes were available as part of the React main package. Type-checking could be easily configured using the built-in prop types property of React.

const ReactComponent = (props) => {
  // ...implement render logic here
};
 
ReactComponent.propTypes = {
  // ...prop type definitions here
};

But after reflecting on the fact that not everybody uses them, the built-in prop types were extracted and made available in a separate package named prop-types. Hence, now accessing prop types via the main react package is deprecated and instead, we need to utilize the prop-types library.

Note: For PropTypes React code migration for v15.4 or below, refer to the official guide here

How to use the prop-types library in React?

Step 1: In order to access the PropTypes utility from React v15.5 and above, you need to add the prop-types library as a dependency in your project. For installing the package, run the following command in the terminal:

  1. For NPM:
npm install prop-types –save
  1. For Yarn:
yarn add prop-types

The package is now installed and you can utilize it to validate any date you are receiving via props. 

Step 2: Next, you need to import PropTypes from the prop-types package to the component files in your project.

import PropTypes from 'prop-types';

Step 3: Once they are imported, you are ready to employ them. Just like default props, PropTypes are also objects where the key is the prop name and the value is the type.

Basic syntax is below:

ReactComponent.propTypes = {
    propName1 : PropTypes.string,
    propName2 : PropTypes.bool,
    propName3 : PropTypes.array,
    .
    .
    .
    propNamen : PropTypes.anyOtherType
}

Using prop types, I have re-written the User component mentioned in the initial example as below:

import React from "react";
import PropTypes from "prop-types";
 
const User = (props) => {
  const { name, age, occupation } = props;
  return (
    <div>
      My name is {name}. I am {age} years old. I am a {occupation}
    </div>
  );
};
 
//Validating prop types
User.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  occupation: PropTypes.string,
};
 
//Defining default props
User.defaultProps = {
  name: "N/A",
  age: 0,
  occupation: "Not Occupied",
};
 
export default User;

Now, if I try passing a wrong type of data to the User component, it will generate console warning.

 <User name="Jill" age={'35'} occupation="Quality Analyst" />

Here, I am passing the age prop in string format and the following warning was thrown in the console.

What are the different types of React PropTypes validators?

The PropTypes React utility exports a range of different validators that can be used to configure type definitions. There are many different types of PropTypes and all of them have their unique classes which you can use. The React prop types validators are categorized below:

  • Basic types
  • Collection types
  • Multiple types
  • Instance types
  • Required types

For advanced type-checking of React props, you can also make use of 

  • Renderable types
  • Custom types

In this section, let us discuss the validators available for type-checking different types of props and understand with examples.

1) Basic Types

As the name suggests, the basic types can be used to validate whether the prop’s type falls under the category of basic or primitive types in JavaScript. Below is the list of validators for the basic types:

  • PropTypes.any: The prop can be of any data type
  • PropTypes.number: The prop should be a number
  • PropTypes.string: The prop should be a string
  • PropTypes.bool: The prop should be a boolean
  • PropTypes.symbol: The prop should be a symbol
  • PropTypes.func: The prop should be a function

Code:

ReactComponent.propTypes = {
  anyProp: PropTypes.any,
  numberProp: PropTypes.number,
  stringProp: PropTypes.string,
  booleanProp: PropTypes.bool,
  symbolProp: PropTypes.symbol,
  functionProp: PropTypes.func
};

2) Collection Types

Other than passing a single data as prop, data can also be passed as a collective type like an  array or object. Let us check out what are the different React Prop Types classes available for type-checking arrays and objects

a. Array Types

  • PropTypes.array: The prop should be an array
  • PropTypes.arrayOf([type]): The prop should be an array where all values match the specified type

Code:

ReactComponent.propTypes = {
  arrayProp: PropTypes.array, // []
  stringArrayProp: PropTypes.arrayOf(PropTypes.string), // ["A","B","C"]
  numArrayProp: PropTypes.arrayOf(PropTypes.number) // [1,2,3]
};

b. Object Types

  • PropTypes.object: The prop should be an object
  • PropTypes.objectOf([type]):  The prop should be an object in which all property values match the specified type.
  • PropTypes.shape: The prop should be an object which contains a set of specified keys with values of the specified types.
  • PropTypes.exact: The prop should be an object which contains a set of specified keys which strictly matches with specified types.

Code:

ReactComponent.propTypes = {
  objectProp: PropTypes.object, // {}
 
  stringObjectProp: PropTypes.objectOf(PropTypes.string), // {name: "John", occupation: "Web Developer"}
  numObjectProp: PropTypes.objectOf(PropTypes.number), // {age: 27}
 
  userObjectShapeProp: PropTypes.shape({
    id: PropTypes.number,
    name: PropTypes.string,
    age:PropTypes.number,
    occupation: PropTypes.string,
  })
 
  userObjectExactProp: PropTypes.exact({
    id: PropTypes.number,
    name: PropTypes.string,
    age:PropTypes.number,
    occupation: PropTypes.string,
  })
};

3) Multiple Types

Using React Prop types validators, you can also allow a limited set of values or multiple sets of a data type for a prop. The validators used for this purpose are: 

  • PropTypes.oneOf: The prop is limited to a specified set of values, treating it like an enum
  • PropTypes.oneOfType: The prop should be one from of a specified set of types, behaving like a union of types

Code:

ReactComponent.propTypes = {
  enumProp: PropTypes.oneOf([true, 23, "N/A"]),
  genderEnumProp: PropTypes.oneOf(["M","F"]),
 
  unionProp: PropTypes.oneOfType([
    PropType.string,
    PropType.array,
    PropType.bool,
    PropType.object,
  ])
};

4) Instance Types

There might be cases where you want the prop to be an instance of a specific JavaScript class. In such cases, you can make use of the instance type validator of PropTypes, which leverages the Javacript instanceof operator internally.

  • PropTypes.instanceOf: The prop should be instance of the specific JS class

Code:

ReactComponent.propTypes = {
  userProp: PropTypes.instanceOf(User)
};

5) Required Types

All the PropTypes React validators we have explored so far allows the prop to be optional by default. In order to make any prop mandatory, all you need to do is chain the prop validator with isRequired. Required types ensure that if the prop isn’t provided, a console warning will be shown.

Code:

ReactComponent.propTypes = {
  requiredString: PropTypes.string.isRequired,
  requiredFunc: PropTypes.func.isRequired,
  requiredObject: PropTypes.object.isRequired
};

For example, I am setting all the props of the User component as mandatory using isRequired, 

User.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
  occupation: PropTypes.string.isRequired,
};

Now, if I make a component call without passing any of the mandatory props, a console warning will be shown,

      <User name="Tom" occupation="Software Engineer" />

If you are a visual learner, I recommend you to checkout this YouTube tutorial for better understanding the concept of React Prop Types.

How to perform advanced type-checking with React PropTypes?

The React Prop Types utility also allows us to perform some advanced type checking on top of basic type checking. In this section, let us explore them.

1) Renderable Types

The Proptypes React validators belonging to the renderable type category focus on the React code rather than the data type. Using renderable types, you can ensure that the value passed to the props can be rendered by React. The different validators available are

  • PropTypes.node: The prop should be anything renderable by React — a number, string, element, array, or fragment containing these types
  • PropTypes.element: The prop should be a React element. You can also use it to specify that only a single child can be passed to the component as children.
  • PropTypes.elementType: The prop should be the name of React components

Code:

ReactComponent.propTypes = {
  nodeProp: PropTypes.node,
  elementProp: PropTypes.element,
  elementTypeProp: PropTypes.elementType
};

2) Custom Validator Types

Finally, React Prop Types also enables us to create our own validators using some custom logic for type checking. In this section, let us discuss them using custom validation function.

The custom validation function takes three arguments

function(props, propName, componentName) {}
  1. props, an object containing all the props passed to the component
  2. propName, the name of the validated prop
  3. componentName, the name of the component

The custom validator requires an Error object that returns if the validation fails. A few things to note about the error object are:

  • The error object should not be thrown.
  • Inside the custom validation function, do not use the console.warn
  • You can also use the custom validators on arrays and objects, but the error will be thrown for each key in the array or object.
PropTypes.arrayOf(function(props, propName, componentName) {})PropTypes.objectOf(function(props, propName, componentName) {})

Let us see an example with the error object. In the User component, I am receiving a prop named “email” which I need to validate using my custom logic. The code will be as below

const validateEmail = function(props, propName, componentName) {
  const regex = /^(?=.*?[#?!@$%^&*-])[A-Za-z\d@$!%*#?&\-\.]{8,16}$/;
 
  if (!regex.test(props[propName])) {
    return new Error(`Invalid prop "${propName}" passed to "${componentName}". Expected a valid email address.`);
  }
}
//Validating prop types
User.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
  occupation: PropTypes.string.isRequired,
  email: validateEmail
};

Now, if I try to pass an email prop of invalid format on the component call, I will receive the warning in the console.

   <User name="Jack" occupation="Data Analyst" age={35} email="ab.com" />

What are the other ways of Static Typechecking in React?

As an alternative mechanism, some developers also make use of the following tools to enforce static type checking in their React app.

Typescript is a syntactic superset of JavaScript developed and maintained by Microsoft. Built on top of JavaScript, it helps developers to add types in JavaScript, which is otherwise a loosely typed language.

On the other hand, Flow is an easy-to-use type check developed by Facebook for React developers. Compared to Typescript, Flow is not an actual programming language but is more like a linter that checks codes for type errors.

If you are wondering which would be the right and optimized type-checking approach for your project, refer to this blog for more insights on the comparison and implementation between Typescript and Flow.

Conclusion

 Type-checking is one of the most powerful practices developers can use for early bug detection and easy debugging during development. React PropTypes is a type checking mechanism provided by React to validate various types of props that a React component recieves and ensure that the right type of props are passed to it.

In this tutorial, we have explored what are React PropTypes and different validators available in prop types along with examples. Hoping this tutorial turned out to be beneficial.

If you are looking out for cool React tools that helps you to write React component code faster and be production ready faster than your competition, don’t forget to checkout the CopyCat plugin for React!

Happy Coding!

Related Articles

  • React.js

    Step-by-Step Guide to using Reactstrap for Building Amazing Web Apps in React

    React still goes strong as one of the most popular JavaScript libraries used for building Single Page Applications (SPAs). The React developers community is very robust and there are a lot of helper tools that can be used with React…

    November 26, 2022
  • React.js

    The Complete Basics of Typescript Record

    Introduction When attempting to incorporate more sophisticated types of data, TypeScript Records are an excellent technique to guarantee consistency. They allow you to provide unique interfaces for the values while enforcing important values. When used to its full potential, TypeScript…

    December 24, 2022

Convert Figma To React

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Convert Design to Code