react js-tutorial

React Props Validation

The mechanism of providing read-only attributes to React components using props is crucial. Usually, the props are necessary for the component to be used correctly. The components could act differently than expected if it is not used properly. Props validation must therefore be used to enhance react components.

Props validation is a tool that will assist the developers in preventing flaws and issues in the future. It is a practical technique to ensure that your components are used correctly. It improves the readability of your code. Although it is not required to define components using propTypes, React components employ a special property called PropTypes that can help you find errors by checking the data types of values supplied through props. However, it is beneficial to use propTypes with your components.

Validating Props

App.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.


class App extends React.Component {  
          render() {}  
Component.propTypes = { /*Definition */};  

import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
  render() {
    return (
        <h1>Welcome to Learn Code Zone!</h1>
        <h2>ReactJS Props validation example</h2>
            <td>{this.props.propArray ? "true" : "False"}</td>
            <td>{this.props.propBool ? "true" : "False"}</td>
            <td>{this.props.propBool ? "true" : "False"}</td>
            <td>{this.props.propFunc(5) ? "true" : "False"}</td>
            <td>{this.props.propString ? "true" : "False"}</td>
            <td>{this.props.propNumber ? "true" : "False"}</td>
// Prop types for our Component
App.propTypes = {
  propArray: PropTypes.array.isRequired,
  propBool: PropTypes.bool.isRequired,
  propFunc: PropTypes.func,
  propNumber: PropTypes.number,
  propString: PropTypes.string,
// Default Props for our Component
App.defaultProps = {
  propArray: [1, 2, 3, 4, 5],
  propBool: true,
  propFunc: function (x) { return x * 10 },
  propNumber: 1,
  propString: "LCZ",
export default App;


Leave a Reply

Your email address will not be published.