ReactJS Props Validation

In this tutorial you will learn about the ReactJS Props Validation and its application with practical example.

ReactJS Props Validation

React comes with an internal mechanism for validating props data type to make sure that values passed through props is valid. React components uses a special property called “propTypes” to setup data type validation. Although, we are allowed to define components without PropTypes. But, with PropTypes we can avoid unexpected bugs or glitches to the users. The PropTypes is provided with props and their respective PropTypes for type-checking. When a prop is passed in with an invalid type or fails the prop type, a warning is passed into the JavaScript console.

Syntax:-

ReactJS Props Validators

The React.PropTypes object contains a list of validators for basic data types –

PropTypes.any :- the prop can be of any data type
PropTypes.bool  :- the prop should be a boolean
PropTypes.number  :- the prop should be a number
PropTypes.string  :- the prop should be a string
PropTypes.func  :- the prop should be a function
PropTypes.array  :- the prop should be an array
PropTypes.object  :- the prop should be an object
PropTypes.symbol  :- the prop should be a symbol
PropTypes.instanceOf :- the prop should be an instance of a particular JavaScript class
PropTypes.isRequired :- the prop should be provided

Example:-

Step 1:- Let’s open src/App.js, delete the existing code and put the following code in it and save it.

Step 2:- Let’s open the terminal again, change directory to your project folder and type the following command in order to run the server.

Step 3:- Now open the following URL in browser to view the output

http://localhost:3000

Step 4:- You will see the following screen.

ReactJS Props Validation

ReactJS Custom Validator

In React, we are allowed to create a custom validation function to perform custom validation as per our requirement. In order to create a custom validation function, we are required to create a function following arguments –

props :- The props passed to the component
propName :- The propName being validated
componentName :- The componentName we’re validating agains

Example:-

In this tutorial we have learn about the ReactJS Props Validation and its application with practical example. I hope you will like this tutorial.