Your experience on this site will be improved by allowing cookies
React Props Validation
Props or “Properties” are read-only components, that gives a way to pass data from one component to other components. It is an immutable object that works similarly to the HTML attributes. The props cannot be modified from inside the component as they are immutable. Thus, it is required to use props validation to make code more readable and to avoid future bugs and problems. Prop validation is a tool that si used to force the correct usage of the components. App.propTypes is used for props validation. It is used to get the warnings on JavaScript console, if the props are passed with an invalid type.
Syntax:
class App extends React.Component { render() {} } Component.propTypes = { /*Definition */};
Props Validators:
PROPSTYPE | VALUES |
PropTypes.any | Any data type. |
PropTypes.array | An array. |
PropTypes.bool | A boolean. |
PropTypes.func | A function. |
PropTypes.number | A number. |
PropTypes.object | An object. |
PropTypes.string | A string. |
PropTypes.symbol | A symbol. |
PropTypes.instanceOf | An instance of a particular JavaScript class. |
PropTypes.isRequired | Must be provided. |
PropTypes.element | Must be an element. |
PropTypes.node | Can render anything: numbers, strings, elements or an array (or fragment) containing these types. |
PropTypes.oneOf() | One of several types of specific values. |
PropTypes.oneOfType([PropTypes.string,PropTypes.number]) | An object that could be one of many types. |
Example:
App.js:
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class App extends React.Component { render() { return ( Validation under process.
|
Main.js:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.js'; ReactDOM.render(, document.getElementById('app')); |
Output:
Validation under process. Type Value Valid Array 54321 true Boolean true true Function 400 true String Hello true Number 10 true |
ReactJS Custom Validators:
To perform custom validation, a custom validation function can be created in ReactJS. A custom validation function in ReactJS contains the following arguments:
0 comments