×

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.
 PropTypes.arrayThe Props should be an array.
 PropTypes.boolThe Props should be a Boolean.
 PropTypes.funcThe Props should be a function.
 PropTypes.numberThe Props should be a number.
 PropTypes.objectThe Props should be an object.
 PropTypes.stringThe Props should be a string.
 PropTypes.symbolThe Props should be a symbol.
 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 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.

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

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

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

React Events An event is an action that triggers a response of the user action or system-generated event. As HTML, React can also perform actions based on user events. React has the...

2 minutes read.

React Portals

React Portals React portals were introduced by React 16.0 in September 2017. It gives you a way to render the element outside of the component hierarchy, i.e., within a separate component. Before React 16.0, it...

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

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.

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

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

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.

ReactJS vs AngularJS

Difference between ReactJS and AngularJS AngularJS AngularJS is the JavaScript framework that is open source, and it is also used to build a dynamic web application. It is developed in 2009 by...

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