×

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 Error Boundaries

React Error Boundaries In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next...

3 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 Animation

React Animation The animation is a procedure in which an image is manipulated to appear as a moving image. It is widely used to create an interactive web application. In React, we have to...

4 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.

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 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.

React JSX

React JSX As we know, all of the React components include a render function. The Render function specifies the HTML output of a React component. JSX is an acronym of JavaScript extension that...

3 minutes read.

React Environment Setup Step by Step

React Environment Setup This section will provide you the information about how to set up an environment for the successful development of ReactJS application: Pre-Requisite for ReactJS NodeJS and NPMReact and React DOMWebpackBabel There are two...

5 minutes read.

React Props

React Props A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute...

3 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 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.

Difference Between State and Props in React

Comparison between State and Props State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over...

2 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.

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 Component Life-Cycle

React Component Life-Cycle In ReactJS, the creation process of every component includes several lifecycle methods. These methods, together stated as component's lifecycle. Four phases of the component's life cycle are as...

4 minutes read.

ReactJS Versions

ReactJS Versions The Complete set of release history of ReactJS is elaborated as follows. The complete set of full documentation of recent releases is on GitHub. S.noVersionRelease DateExplanation1.0.3.029/05/2013Initially released for public.2.0.4.029/07/2013Supporting comments...

4 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.

Difference Between React Flux and MVC

React Flux vs MVC MVC MVC is an acronym of 'Model View Controller.' It is the architectural pattern that is used to develop the user interface. It has three different logical components: The...

2 minutes read.

React State

React State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over time. The change...

3 minutes read.

React Constructors

What is constructor? The constructor is a method that is used for initializing the state of the object in the class. It calls automatically during the creation of an object in...

4 minutes read.