Props Validation
Props Validation
Props Validation is all about validating to props. As if you want to pass default value to property or you want to make any property mandatory then that is done by use of validation. Implementation is as below-:
In this there are many properties used. Whenever you create a property then it’s mandatory to define the validation if required with some value you want to set. If you want to pass something which is important for user to pass then “.isRequired” is used.
Import PropTypes from ‘prop-types’;
Import React from ‘react’;
Import ReactDOM from ‘react-dom’;
Class App extends React.Component {
Render() {
< div>
< h1>Hello, {this.props.name} < /h1>
< h3>Array: {this.props.propArray}< /h3>
< h3>Func: {this.props.propFunc}< /h3>
< h3>Number: {this.props.propNumber}< /h3>
< h3>String: {this.props.propString}< /h3>
< /div>
};
}
}
App.propTypes = {
Name: PropTypes.string,
propArray: PropTypes.array.isRequired,
propFunc: PropTypes.func,
propNumber: PropTypes.number,
propString: PropTypes.string,
};
App.defaultProps = (
Name= ‘ducat.com’,
propArray: [1, 2, 3, 4, 5,];
propFunc: function=(e) {
return e
};
propNumber: 1,
propString: “String value...”
};
Export default App;
So here so many properties are created. Whenever you create property you have to define the validation if required and you have to set some default value for particular properties. Here in prop type datatypes are put for each of the property like string, array, number, Boolean. If you want that something compulsory you have to pass that “isRequired” is used. You can initialise all the properties with the default value like in function (e) same “e” is returning or you can pass particular value you want by default.
Output is as-:
React Custom Validator
Custom validation can also be performed when required. Following arguments are used for custom validation-:
Props, PropName, ComponentName
For Example-: