How to apply validation on Props in ReactJS ?
Last Updated :
30 Nov, 2023
Need of Validating Props in React JS Props are used to pass the read-only attributes to React components. For the proper functioning of components and to avoid future bugs and glitches it is necessary that props are passed correctly. Hence, it is required to use props validation to improve the react component's performance.
Prerequisites:
Syntax: The syntax to use propTypes is shown below.
class Component extends React.Component {
render() {}
}
Component.propTypes = {/* definition goes here*/};
Validators: The propTypes object contains a list of validators for basic data types, some of them are:
- PropTypes.any : This means the prop can be of any data type.
- PropTypes.bool: This means the prop should be a boolean.
- PropTypes.number: This means the prop should be a number.
- PropTypes.string: This means the prop should be a string.
- PropTypes.func: This means the prop should be a function.
- PropTypes.array: This means the prop should be an array.
- PropTypes.object: This means the prop should be an object.
- PropTypes.symbol: This means the prop should be a symbol.
- PropTypes.instanceOf: This means the prop should be an instance of a particular JavaScript class.
- PropTypes.isRequired: This means the prop should be provided.
- PropTypes.oneOf(): This means the props should be one of several types of specified values.
- PropTypes.element: This means the props must be an element.
Steps to Create the React Application And Installing Module:
Step 1: Create a React application by typing the following command in the terminal:
npx create-react-app PropValidation
Step 2: After creating your project folder i.e. PropValidation, move to it using the following command:
cd PropValidation
Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install prop-types
Project Structure:
Project StructureThe updated dependencies in package.json file will look like:
"dependencies": {
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Here we have defined the props types for our component as well as the default props.
JavaScript
import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
render() {
return (
<div>
<h1>Welcome to GFG!!</h1>
<h2>ReactJS Props validation example</h2>
<table>
<tr>
<th>Type</th>
<th>Value</th>
<th>Valid</th>
</tr>
<tr>
<td>Array</td>
<td>{this.props.propArray}</td>
<td>{this.props.propArray ? "true" : "False"}</td>
</tr>
<tr>
<td>Boolean</td>
<td>{this.props.propBool ? "true" : "False"}</td>
<td>{this.props.propBool ? "true" : "False"}</td>
</tr>
<tr>
<td>Function</td>
<td>{this.props.propFunc(5)}</td>
<td>{this.props.propFunc(5) ? "true" : "False"}</td>
</tr>
<tr>
<td>String</td>
<td>{this.props.propString}</td>
<td>{this.props.propString ? "true" : "False"}</td>
</tr>
<tr>
<td>Number</td>
<td>{this.props.propNumber}</td>
<td>{this.props.propNumber ? "true" : "False"}</td>
</tr>
</table>
</div>
);
}
}
// Prop types for our Component
App.propTypes = {
propArray: PropTypes.array.isRequired,
propBool: PropTypes.bool.isRequired,
propFunc: PropTypes.func,
propNumber: PropTypes.number,
propString: PropTypes.string,
}
// Default Props for our Component
App.defaultProps = {
propArray: [1, 2, 3, 4, 5],
propBool: true,
propFunc: function (x) { return x * 10 },
propNumber: 1,
propString: "GFG",
}
export default App;
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:
Output Image
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read