Validate React Prop

March 29, 2020

You can validate the property of a React component using the built in PropTypes

import React from "react";
import { PropTypes } from "prop-types";

export class Setting extends React.Component {
  render() {
    return (
      <div>
        <ul>
          <li>{this.props.title}</li>
        </ul>

        <table>
          <tr>
            <td> Currency </td>
            <td> {this.props.currency} </td>
          </tr>
          <tr>
            <td> Rows Per Page </td>
            <td> {this.props.rowsperpage} </td>
          </tr>
        </table>
      </div>
    );
  }
}

Setting.defaultProps = {
  rowsperpage: 20,
  currency: "USD"
};

Setting.propTypes = {
  rowsperpage: PropTypes.number,
  currency: PropTypes.string
};

export default Setting;

When i pass the following props to the component

When there are validation errors they will be shown in the console as warning message

Warning: Failed prop type: Invalid prop `rowsperpage` of type `string` supplied to `Setting`, expected `number`.