C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
React Props ValidationProps are an important mechanism for passing the read-only attributes to React components. The props are usually required to use correctly in the component. If it is not used correctly, the components may not behave as expected. Hence, it is required to use props validation in improving react components. Props validation is a tool that will help the developers to avoid future bugs and problems. It is a useful way to force the correct usage of your components. It makes your code more readable. React components used special property PropTypes that help you to catch bugs by validating data types of values passed through props, although it is not necessary to define components with propTypes. However, if you use propTypes with your components, it helps you to avoid unexpected bugs. Validating PropsApp.propTypes is used for props validation in react component. When some of the props are passed with an invalid type, you will get the warnings on JavaScript console. After specifying the validation patterns, you will set the App.defaultProps. Syntax:class App extends React.Component { render() {} } Component.propTypes = { /*Definition */}; ReactJS Props ValidatorReactJS props validator contains the following list of validators.
ExampleHere, we are creating an App component which contains all the props that we need. In this example, App.propTypes is used for props validation. For props validation, you must have to add this line: import PropTypes from 'prop-types' in App.js file. App.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; class App extends React.Component { render() { return ( Main.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.js'; ReactDOM.render( Output: ReactJS Custom ValidatorsReactJS allows creating a custom validation function to perform custom validation. The following argument is used to create a custom validation function.
Examplevar Component = React.createClass({ App.propTypes = { customProp: function(props, propName, componentName) { if (!item.isValid(props[propName])) { return new Error('Validation failed!'); } } } })
Next TopicState Vs Props
|