Monday, March 7, 2022

How to do Type checking in React using PropTypes? Example Tutorial

In React, data can be passed from a parent component to a child component as props. Props are the properties that contain immutable read-only data. A prop value is basically an object which can hold any number of values of different data types. Props are an essential part of a React application. If not handled properly, props can lead to potential bugs and conflicts. The main issue is the data type of the value that is being passed from one component to another. React provides type checking support that is very useful in such cases. In this article, we will discuss how to use type checking in React with the help of PropTypes. 



What is type checking and why it is required?

In simple words, type checking is checking the type of a particular value. Suppose, a component is expecting a numerical value for some calculations. What if the value passed from the parent component is a string or boolean? It will result in unwanted output, right? So to avoid such conflicts and unwanted situations, type checking is recommended.

In React, PropTypes could be used to add type checking in a component. 



PropTypes

As mentioned above, PropTypes is used in React for type checking. Let’s understand with the help of an example.

Observe the following data.

const data = [

  {

    name: "John",

    age: 29,

    city: "New York"

  },

  {

    name: "Mike",

    age: 31,

    city: "Detroit"

  },

  {

    name: "Lisa",

    age: 25,

    city: "Chicago"

  }

];

export default data;


Now, observe the App.js file.

import "./styles.css";

import data from "./data.js";

import Employee from "./Employee.js";

export default function App() {

  const employeeDetails = data;

 

  return (

    <div className="App">

      {employeeDetails.map((employee) => {

        return <Employee employeeData={employee} />;

      })}

    </div>

  );

}


In the App component, “data” is imported and stored in “employeeDetails”. Then, the “employeeDetails” is used to render the details of every employee using the map function in the “Employee” component.


Observe the props passed to the Employee component.


<Employee employeeData={employee} />


“employee” is an object. Let’s check the Employee component.


function Employee(props) {

 return (

   <>

     <h3>Name: {props.employeeData.name} </h3>

     <h3>Age: {props.employeeData.age} </h3>

     <h3>City: {props.employeeData.city} </h3>

     <hr />

   </>

 );

}

export default Employee;


Here, the props are used to render all the values of an object. 



Now, let’s introduce one small error in the App.js file. 


{employeeDetails.map((employee) => {

return <Employee employeeData={employee.name} />;

})}


Instead of passing the “employee” object, we are passing the “employee.name” i.e. a string


Let’s check the output.



Obviously, no data is rendered. Now, suppose, this was a huge application. How would you know what went wrong? Here comes the concept of type checking. 


The Employee component is expecting an object. So it’s a perfect place to add the type checking.

First, we need to install “prop-types” using the following command. 


npm install prop-types


Now, observe the following code. 


import PropTypes from "prop-types";

 

function Employee(props) {

  return (

    <>

      <h3>Name: {props.employeeData.name} </h3>

      <h3>Age: {props.employeeData.age} </h3>

      <h3>City: {props.employeeData.city} </h3>

      <hr />

    </>

  );

}

 

Employee.propTypes = {

  employeeData: PropTypes.object,

};

 

export default Employee;


First, “PropTypes” is imported, and then, it is used with the Employee component,


Employee.propTypes = {

  employeeData: PropTypes.object,

};


The above code signifies that “employeeData” should be an object. It does not make any changes in the UI but it will display a warning in the console. 



The warning message states what is wrong. So this is how type checking can be useful to find the bugs and errors. Similarly, propTypes can be used on any kind of data type.




Default props

What if no props are passed from the App component to the Employee component? The PropType is useless in such situations. So to encounter such situations, React provides default props. 


Observe the return statement of the App.js file.


return (

 <div className="App">

   {employeeDetails.map((employee) => {

     return <Employee />;

   })}

 </div>

);


No props are passed. So let’s define default props in the Employee component. 


import PropTypes from "prop-types";

 

function Employee(props) {

  return (

    <>

      <h3>Name: {props.employeeData.name} </h3>

      <h3>Age: {props.employeeData.age} </h3>

      <h3>City: {props.employeeData.city} </h3>

      <hr />

    </>

  );

}

 

Employee.propTypes = {

  employeeData: PropTypes.object,

};

 

Employee.defaultProps = {

  employeeData: {

    name: "Default name",

    age: "Default age",

    city: "Default city",

  },

};

 

export default Employee;


Observe the following piece of code. 


Employee.defaultProps = {

  employeeData: {

    name: "Default name",

    age: "Default age",

    city: "Default city",

  },

};


This signifies, if no props are passed, then set the value of “employeeData” equal to the object specified. 


Let’s check the output. 



The value corresponding to every field is equal to the default value. 




Wrapping it up

Type checking with PropTypes is a very useful concept because it helps us locate where the bug is. Moreover, we can also use default props to assign default values to the props if they are not passed. 


Other React.js  Articles and Tutorials you may like

Thanks for reading this article so far. If you like this React tutorial about type shcecking in REact.js, please share it with your friends and colleagues. IF you have any questions or feedback, then please ask in comments. 


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.