Type Checking with PropTypes

Gunjeev Singh
Last Updated: May 13, 2022

Introduction

One of the most powerful features of ReactJS is the ability to pass data to various components just like arguments are passed in a function. React developers use the concept of props very often. Props give us the ability to pass data from one component to another and hence render dynamic data. We can pass data across a spectrum of types. We can pass integers, strings, symbols, arrays, and even objects as props to different components. 

To learn more about how props function, you can check this blog out!

 

This comes up with a lot of vulnerabilities. A lot of times, it is vital to check what type of data is being transferred. Validating information is also crucial at times. This is where PropTypes comes up. Type checking with PropTypes is an essential feature of ReactJS, and through this blog, we will look into how to implement it. 

Why PropTypes?

We have discussed why we need to check the vulnerabilities in data passed as props in different components. In Javascript, data types are defined by the information we store in variables. For example, if we define a variable new and keep 20 in it, it currently holds an integer, but if we update its value to "Hello," it will not throw an error but simply change the type of data that the variable holds.

 

var new = 20; // This stores an integer
new = "Hello"; // Data type changed to string  

 

Since React is also based on Javascript, this same issue arises with React as well. In simple terms, there is no way to check the type of data that is being passed in props until the data is rendered on the browser window. This is why React offers us PropTypes. PropTypes is a feature that provides a range of checks that validate data types. Type checking will send us a warning on the console if the rendered data type is different from what we had initially specified. 

 

PropTypes is only available in a React application development build and not the production build for obvious performance-related reasons. 

Implementing PropTypes in React

Before we learn how to implement PropTypes in React, we need to install the npm prop-types package first. 

 

Using npm:
npm install prop-types --save


Using Yarn:
yarn add prop-types 

 

To understand the primary use case of PropTypes, we will use the help of the following example. 

 

If we use PropTypes to validate a variable as an integer but intentionally pass a string to it, even though everything would be perfectly rendered on the browser, the console would have a warning message. 

 

import React from 'react';
import ReactDOM from 'react-dom';
// We need to import the PropTypes package before  using it.
import PropTypes from 'prop-types'; 


// Using a Class based Component
class ExampleOne extends React.Component{
    render(){
        return(
        <div>
        {/* printing all props */}
        <h1>
        {this.props.exampleProp}
        </h1>
        </div>
    );
}
}


// Validating prop types
ExampleOne.propTypes = {
exampleProp: PropTypes.number // Validating it as a number
}


// Creating default props
ExampleOne.defaultProps = {
exampleprop: "String as Example"
}


ReactDOM.render(
    <ExampleOne />,
    document.getElementById("root")
);

 

When we run this application, "String as Example" is rendered as a <h1> tag on the browser. But, along with that, the console throws a warning which says that exampleProp is supposed to be an integer. This is extremely helpful when we need to debug our react code.

 

Console error thrown when the above code is run

 

This example taught us how to use PropTypes in a class-based react component. 

Default Prop Values

In the above example, you can see that we have used a defaultProps() function. This method is a pre-built React entity. Using defaultProps(), we can define default values to our props. The defaultProps() would ensure that the variable has a value in case the parent component does not define it. TypeChecking with PropTypes also works on default props. 

 

// Creating default props
ExampleOne.defaultProps = {
exampleprop: "String as Example"
}

Static PropTypes

A new feature that was absent till the ES5 engine is the static keyword. The static property changes the implementation in such a way that the validation using propTypes goes directly into the class name, not the instance of the class.

 

// Creating static default props
static defaultProps = {
exampleprop: "String as Example"
}

Using PropTypes in Functional Components

PropTypes can be directly implemented inside function-based react components. Let us learn the implementation through the following example:

 

import React from 'react'
import PropTypes from 'prop-types'


// Function-based component
function ExampleTwo(props) {
return (
    <div>
        {/* Printing the props */}
        <h1>
        {props.exampleProp}
        </h1>
    </div>
)
}


// Creating default props
ExampleTwo.defaultProps = {
exampleProp: "String as Example"
}


// Validating prop types
ExampleTwo.propTypes = {
exampleProp: PropTypes.number
}


export default ExampleTwo;

 

We have implemented the same code as Example One in the above example but using a function-based react component. If you look carefully, you will notice that we can implement PropTypes directly inside the function itself. The output is as expected. "String as Example" gets rendered on the browser in a <h1> tag, but the console throws a warning. 

 

Warning thrown by console 

 

This is how PropTypes can be implemented in React. Given below is a list of PropTypes validations that react offers developers.

List of Various PropTypes Validations

Given below is a list of some commonly used PropTypes variations.

  • PropTypes.func: This validates whether the prop is a function.
  • PropTypes.array: This validates whether the prop is an Array.
  • PropTypes.number: This validates whether the prop is a number.
  • PropTypes.object: This validates whether a prop is an Object.
  • PropTypes.string: This validates whether the prop is a string.
  • PropTypes.bool: This validates whether the prop is a bool.

Frequently Asked Questions

1. What is the PropTypes.element property?
The PropTypes.element property is a pre-built method in React prop-types that ensures that only a single child is passed to the parent component.

 

2. Can we use PropTypes if we are directly exporting the component?
No! To use PropTypes, components must be defined in separate functions and then exported separately, as shown in the examples above.

 

3. What is the use of isRequired?

The isRequired tag ensures that the prop is being sent. If that prop isn’t provided, a warning is shown on the console. 

 

4. What is the difference between props and propType?

Props in React are the arguments or data that we pass to different components. On the other hand, propTypes is a feature of React that allows us to validate what type of data is being passed as props. 

Key Takeaways

This blog explained the concept of TypeChecking with PropTypes in React. To sum it up, we need PropTypes because, in Javascript, the data type of variables is determined only at the time of execution. PropTypes help us check what kind of data is being passed through props in different components. We also looked into the implementation of PropTypes in both class and function-based react components. 

 

To become an even better React developer, you can use the following course!

Was this article helpful ?
1 upvote

Comments

No comments yet

Be the first to share what you think