In our previous article ReactJS Typechecking With PropTypes – Set 1, we discussed how to use PropTypes for validating any data we are receiving from props. But our discussion was limited only to validating the data types such as an array, string, object, or number. In this article, we will extend our discussion and learn how to validate React elements (such as an instance of a class), specific and multiple values, shapes, and types, and exact validation of the data inside a prop.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Required module: Before using PropTypes we will have to install it by typing the given command in the terminal.
npm install prop-types --save
Example 1: Instance Validation with propTypes
We can validate the instance of our prop, i.e., check if the prop is an instance of a class or not. Let’s look at an example to understand this in a better way.
App.js
import React, {Component} from 'react' ; import PropTypes from 'prop-types' ; // Sample class class Sample { constructor(value) { this .price = value.price; } } // Component class SamplePrice extends Component { render() { return ( <div> <h1> { this .props.priceProp} </h1> </div> ) } } // Creating default props SamplePrice.defaultProps = { priceProp: "neveropen" } // Validating the props SamplePrice.propTypes = { priceProp: PropTypes.instanceOf(Sample) } // Export the Component export default SamplePrice; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Explanation: You can see in the above program that we are passing the prop named priceProp as a string in a class component and validating it as an instance of the user-defined class Sample, even then everything is rendered perfectly on the browser. But our browser console has a warning message. This message clearly tells us that the prop named priceProp was expected to be an instance of class Sample but instead a string value is passed.
Example 2: Specific and Multiple values validation
We can validate that our props must be some specific values, i.e., its value must be one of the values provided in the collection. We can also specify that our prop could be of any type that are given in the collection.
App.js
import React, { Component } from 'react' import PropTypes from 'prop-types' // Component class ProfitComponent extends Component { render() { return ( <div> { /* printing the props */ } <h1> { this .props.goods} </h1> <h1> { this .props.cost} </h1> </div> ) } } // Creating default props ProfitComponent.defaultProps = { goods: 10, cost: "Geeks" } // Validating prop types ProfitComponent.propTypes = { // Specific validation goods: PropTypes.oneOf([50, 'Photos' ]), // Multiple validation cost: PropTypes.oneOfType([ PropTypes.array, PropTypes.number ]) } export default ProfitComponent; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Explanation: You can see in the above program that we are passing the prop named goods as a number 10 in a class component and validating if it has an exact value of a number 50 or a string “Photos”, even when everything is rendered perfectly on the browser. But our browser console has a warning message. This message clearly tells us that the prop named goods were expected to have an exact value of either 50 or “Photos” but instead, a value of 10 is passed. This is called Specific Value validation, i.e., the prop must have the same data type as well as the same value.
We are also passing the prop named cost as a string and validating if it is an array or a number, even when everything is rendered perfectly on the browser. But our browser console has a warning message. This message clearly tells us that the prop named cost was expected to be an array or a number but instead a string is passed. This is called Multiple Value Validation, i.e., the prop must be of one of the data types provided in the collection, but it can have any value.
Example 3: Types and shapes validation
We can specify a prop to be of type array and further validate that the array values are of a certain type or not. We can also do it for more than one data type using shape validation.
App.js
import React, {Component} from 'react' ; import PropTypes from 'prop-types' ; // Component class SamplePrice extends Component { render() { return ( <div> <p>Type Validation</p> <h1> { /* Printing the props */ } { this .props.ArrayProp.map((item, index)=>{ return ( <p key={index}>{item}</p> ) }) } </h1> <p>Shape Validation</p> <h1> { this .props.ShapeOfProp.CarName} </h1> <h1> { this .props.ShapeOfProp.Price} </h1> </div> ) } } // Creating default props SamplePrice.defaultProps = { ArrayProp: [ "Car" , "Driver" , "Cost" ], ShapeOfProp: ({CarName: "Ferrari" , Price: "56" }) } // Validating the props SamplePrice.propTypes = { // Types validation ArrayProp: PropTypes.arrayOf(PropTypes.number), // Shapes validation ShapeOfProp: PropTypes.shape({ CarName: PropTypes.string, Price: PropTypes.number }) } // Export the Component export default SamplePrice |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Explanation: You can see in the above program that we are passing the prop named ArrayProp as an array of strings in a class component and validating it as an array of numbers, even when everything is rendered perfectly on the browser. But our browser console has a warning message. This message clearly tells us that the prop named ArrayProp was expected to be an array of numbers but instead it is passed as an array of strings. This is called Types validation, i.e., we can validate the data that we are passing inside another data type (ex array, object).
We are also passing the prop named ShapeOfProp as an object having two parameters CarName and Price expected to have a value of string and number respectively. Our browser gives us a warning message for the Price parameter as we have passed 56 as a string, not a number. This is called Shape Validation, i.e., we can validate the data we are passing into each data type.
Example 4: Exact parameters validation
We can specify the number of parameters we can provide in an object passed as props. This is done by exact method.
App.js
import React, { Component } from 'react' import PropTypes from 'prop-types' // Component class ProfitComponent extends Component { render() { return ( <div> { /* Printing the props */ } <h1> { this .props.goods.name} </h1> <h1> { this .props.goods.quantity} </h1> <h1> { this .props.goods.info} </h1> </div> ) } } // Creating default props ProfitComponent.defaultProps = { goods: ({ name: "GeeksForGeeks" , quantity: 20, info: "Cars Data" }) } // Validating prop types ProfitComponent.propTypes = { goods: PropTypes.exact({ name: PropTypes.string, quantity: PropTypes.number }) } export default ProfitComponent; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Explanation: You can see in the above program that we are passing the prop named goods as an object array having three parameters (name, quantity, and info) and validating it as an object having only two parameters (name and quantity), even when everything is rendered perfectly on the browser. But our browser console has a warning message. This message terms our object as a bad object and clearly tells us that the prop named goods were expected to have exactly two parameters but instead, it is having three parameters (one extra parameter). This is called Exact parameters validation, i.e., we can decide how many parameters we are going to pass inside an object.
Note: We are almost done with Typechecking with Props. You must be wondering how to make sure that a prop is provided or validate our prop with a user-defined function. We will learn about these in detail in the next article ReactJS Typechecking With Props – Set 3.