×

React Props Validation

React Props Validation

As we know, props are a suitable mechanism for passing the read-only attributes to react components. The props are required to be correctly used in the component. If it is not correctly used, behavior of the component may not as expected. Therefore, it is essential to use props validation in improving react components.

Props validation is a tool that helps developers for avoiding future bugs and problems. It makes the code more readable. There is a special property used in React components that is PropTypes, which helps you in catching the bugs by validating data types of values passed through props, but it is not necessary to define components with PropTypes. However, if you are using PropTypes with your components, it will help you to avoid the unexpected bugs.

Validating Props

App.propTypes is used for validating the props in the react component. When an invalid type passes any of the props, it will show the warnings on the console of the JavaScript. Once the validation patterns are described, you will set the App.defaultProps.

Syntax:

class App extends React.Component {
render() {}
} 
Component.propTypes = { /*Definition */};

Example:

In this example, there is an App component that contains all the props that we require. Here, App.propTypes is used for validating the props. For validating the props, you have to add the line: import PropTypes from ‘prop-types’ in the App.js file.

App.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class App extends React.Component {
  render() {
    return (
      <div>
        <h2>ReactJS Props validation example</h2>
        <table>
          <thead>
            <tr>
              <th>Type</th>
              <th>Value</th>
              <th>Validity</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Boolean</td>
              <td>{this.props.propBool ? "true" : "false"}</td>
              <td>{this.props.propBool ? "true" : "false"}</td>
            </tr>
            <tr>
              <td>Array</td>
              <td>{this.props.propArray}</td>
              <td>{this.props.propArray ? "true" : "false"}</td>
            </tr>
            <tr>
              <td>Function</td>
              <td>{this.props.propFunc(2)}</td>
              <td>{this.props.propFunc(2) ? "true" : "false"}</td>
            </tr>
            <tr>
              <td>Number</td>
              <td>{this.props.propNumber}</td>
              <td>{this.props.propNumber ? "true" : "false"}</td>
            </tr>
            <tr>
              <td>String</td>
              <td>{this.props.propString}</td>
              <td>{this.props.propString ? "true" : "false"}</td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  }
}

App.propTypes = {
  propBool: PropTypes.bool.isRequired,
  propArray: PropTypes.array.isRequired,
  propFunc: PropTypes.func,
  propNumber: PropTypes.number,
  propString: PropTypes.string,
};

App.defaultProps = {
  propBool: false,
  propArray: [2, 4, 6],
  propFunc: function(x) { return x + 5; },
  propNumber: 6 - 6,
  propString: "Hello",
};

export default App;

Main.js

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import App from './App.js'; 

ReactDOM.render(<App />, document.getElementById('app'));

Output:

Reactjs props validation Example

ReactJS Props Validators

The list of ReactJS props validators are as follows:

S.no.PropsTypeDescription
1 PropTypes.anyThe Props can be of any data type.
2  PropTypes.arrayThe Props should be an array.
3  PropTypes.boolThe Props should be a Boolean.
4  PropTypes.funcThe Props should be a function.
5  PropTypes.numberThe Props should be a number.
6  PropTypes.objectThe Props should be an object.
7  PropTypes.stringThe Props should be a string.
8  PropTypes.symbolThe Props should be a symbol.
9  PropTypes.instanceOfThe Props should be an instance of a particular JavaScript class.
10  PropTypes.isRequiredThe Props must be provided.
11  PropTypes.elementThe Props must be an element.
12  PropTypes.nodeThe props can render anything: numbers, strings, or the array (or fragment) that contains these types.
13  PropTypes.oneOf()The Props should be one of several types of specific values.
14  PropTypes.oneOfType([PropTypes.string,PropTypes.number])The Props should be an object that has one of many types.

Related Topics

React Map

React Map The map() is the standard function of JavaScript, which can be called at any array. The map() method is used for traversing and displaying a list of the similar objects of...

2 minutes read.

React Hooks

React Hooks The Hooks were introduced in React 16.8. By using React Hooks, you can use the state and other features of the React without writing a class. Hooks do not work within the classes....

5 minutes read.

Features of ReactJS

ReactJS Features As of now, within the developers, ReactJS is gaining much popularity as the best JavaScript framework. It is crucial for the front-end ecosystem. There are some of the crucial features of ReactJS that are...

2 minutes read.

React Higher-Order Components

React Higher-Order Components In short form, Higher-Order Components are represented as HOC. The Higher-order component is an advanced technique to use component logic. HOC is a function that takes the component and returns the new...

2 minutes read.

Comparison between React and Vue

Comparison between React and Vue React, and Vue both are the two most famous libraries of JavaScript that are used for creating thousands of websites today. The React and Vue both...

3 minutes read.

React Table

React Table The table represents an arrangement that organizes the information in the form of rows and columns. The table is mainly used for storing and displaying the data within a structured format. Features of...

2 minutes read.

React Flux

React Flux Introduction It is an application architecture that is internally used by Facebook to build the client-web application with react. It is useful when the project includes dynamic data, and...

2 minutes read.

React CSS

What is React CSS React CSS is used to provide the style to the React applications. The style attribute adds dynamically-computed styles at render time, and it is one of the most used...

5 minutes read.

React Lists

React Lists Lists are used for displaying the data in an ordered format and mainly used to display the menus on websites. The creating of lists in React is as similar...

2 minutes read.

React Fragments

React Fragments The fragments in React are introduced from the 16.2 and above versions. Fragments allow you to group a list of child elements without adding any extra node in the DOM. In React,...

2 minutes read.

How to use React Context

React Context React Context is used to pass the data through the component tree without passing the props down manually at the every level. In React Application, the data is passed in a top-down approach...

4 minutes read.

React Props Validation

React Props Validation As we know, props are a suitable mechanism for passing the read-only attributes to react components. The props are required to be correctly used in the component. If it is...

5 minutes read.

ReactJS Tutorial

ReactJS Introduction React Tutorial helps you to understand the basic and some advanced concepts of ReactJS. As of now, it is the essential front-end library that is developed by a...

3 minutes read.

React Refs

React Refs The word ‘Refs’ is an abbreviation of ‘References’ in React. It is as similar as Keys in React. Refs are a function in React which is used for accessing the DOM element and...

7 minutes read.

React Router

What is React Router? Routing is a process by which a user can direct to different pages based on their actions and requests. ReactJS router is generally used to develop single...

10 minutes read.

React Redux

How to Use Redux with React Hooks It is an open-source library of JavaScript which is used for managing the application state. React uses the Redux to build the user interface....

5 minutes read.

React Forms

React Forms Forms are the important part of any web application. It allows the interaction of the user with the app as well as the gathering of the information from the...

3 minutes read.

React Components

React Components Former, the developers used to write more than thousands of lines of code to develop a single-page application. These applications follow the structure of traditional DOM, and it was very challenging to make...

2 minutes read.

React Keys

React Keys A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful...

3 minutes read.

React Component API

React Component API It is a top-level API. It provides reusability to the code in the application and makes it completely individual. It has several methods for: Creating Elements.Transforming Elements.Fragments. Now, we are explaining the three...

2 minutes read.