Home >>ReactJS Tutorial >ReactJS Props Validation

ReactJS Props Validation

ReactJS Props Validation

Validating Props

In this example, we build a component of the App with all the props we need. App.propTypes is used for validation of props. If any of the props don't use the correct type we've assigned, we will get a warning from the console. We'll set App.defaultProps after we define the validation patterns.


import React from 'react';

class App extends React.Component {
   render() {
      return (
            <h3>Array: {this.props.propArray}</h3>
            <h3>Bool: {this.props.propBool ? "True..." : "False..."}</h3>
            <h3>Func: {this.props.propFunc(3)}</h3>
            <h3>Number: {this.props.propNumber}</h3>
            <h3>String: {this.props.propString}</h3>
            <h3>Object: {this.props.propObject.objectName1}</h3>
            <h3>Object: {this.props.propObject.objectName2}</h3>
            <h3>Object: {this.props.propObject.objectName3}</h3>

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

App.defaultProps = {
   propBool: true,
   propFunc: function(e){return e},
   propNumber: 1,
   propString: "String value...",
   propArray: [1,2,3,4,5],
   propObject: {
      objectName2: "objectValue2",
      objectName3: "objectValue3"
export default App;

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));

reactjs Props Validation

No Sidebar ads