React Props Validation

1.Introduction:

1.Props are an important mechanism for passing the read-only attributes to React components.
2.props validation is required because if they are not used correctly inside components, then components may not behave as expected.
3.props validation a useful way to force the correct usage of your components.
4.App.propTypes is used for props validation.
5.If any of the props aren’t using the correct type that we assigned, we will get a console warning when we use App.propTypes.

Below are the some react props validators:

  • PropTypes.any – The props can be of any data type.
  • PropTypes.array – The props should be an array.
  • PropTypes.bool – The props should be a boolean.
  • PropTypes.func – The props should be a function.
  • PropTypes.number – The props should be a number.
  • PropTypes.object – The props should be an object.
  • PropTypes.string – The props should be a string.
  • PropTypes.symbol – The props should be a symbol.
  • PropTypes.instanceOf – The props should be an instance of a particular JavaScript class.
  • PropTypes.isRequired – The props must be provided.
  • PropTypes.element – The props must be an element.
  • PropTypes.node – The props can render anything: numbers, strings, elements or an array (or fragment) containing these types.
  • PropTypes.oneOf() – The props should be one of several types of specific values.
  • PropTypes.oneOfType([PropTypes.string,PropTypes.number]) – The props should be an object that could be one of many types.

Let us better understand props validatiors using simple code.

we can use app.defaultProps to set dafault data to props.

App.jsx

import React from 'react';
import PropTypes from 'prop-types'; 
class App extends React.Component {
   render() {
      return (
         <div>
         <p><b>Prop Types: Data</b></p>
         <p>  Props Array: {this.props.propArray}</p>
         <p>   Props Bool: {this.props.propBool ? "True..." : "False..."}</p>
         <p>   Props Func: {this.props.propFunc(1)}</p>
         <p> Props Number: {this.props.propNumber}</p>
         <p> Props String: {this.props.propString}</p>
         <p> Props Object: {this.props.propObject.objectName}</p>
         </div>
      );
   }
}

App.propTypes = {
   propArray: PropTypes.array.isRequired,
   propBool: PropTypes.bool.isRequired,
   propFunc: PropTypes.func,
   propNumber: PropTypes.number,
   propString: PropTypes.string,
   propObject: PropTypes.object
}

App.defaultProps = {
   propArray: [1,2,3,4,5],
   propBool: true,
   propFunc: function(e){return e},
   propNumber: 1,
   propString: "this is String...",
   propObject: {
      objectName:"this is react props object",
   }
}
export default App;


main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));