×

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

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.

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

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

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

Difference between Controlled and Uncontrolled component in ReactJs

Controlled Component In the controlled component, the input of the form element is handled by the component rather than the DOM. Controlled components have the functions that govern the data, which...

2 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 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 Conditional Rendering

React Conditional Rendering In React, the working of the conditional rendering is similar to the condition works in JavaScript. We use JavaScript operators for creating elements that represent the current state, and then the React...

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

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