DEV Community

Cover image for The Beginner's Guide To React: Validation of Custom React Component Props with PropTypes
Bipin Rajbhar
Bipin Rajbhar

Posted on • Updated on

The Beginner's Guide To React: Validation of Custom React Component Props with PropTypes

React is a JavaScript library and JavaScript does not provide any type checking. You can use JavaScript extensions like Flow and TypeScript for type checking. But if you do not want to use those, React provides build-in type checking capability. To run type checking on the props for a component you can assign the special propTypes property.

Custom Props Validator

I am sure you will not create your own props validator in the future because the React team already created a package called PropTypes for props validation.

Creating our own props validator

// Custom props validator
const PropTypes = {
  string(props, propName, componentName) {
    if (typeof props[propName] !== "string") {
      return new Error(
        `Hey, the component ${componentName} need the prop ${propName} to be a string, but you passed a ${typeof props[
          propName
        ]}.`
      );
    }
  }
};

Using Custom Props Validator

To run type checking on the props for a component we need to assign the special property called propTypes.

// Using custom props validator
MyComponent.propTypes = {
  firstName: PropTypes.string
};

Here the propsTypes is an object which stores the data in key-value pairs where the key is the name of the property and the value is the type of the property that can be passed to the component.

Example

 <body>
    <div id="root">This will be replace by React</div>

    <script src="https://unpkg.com/react@16.13.1/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.9.4/babel.js"></script>
    <script type="text/babel">
      const rootElement = document.getElementById("root");

      // functional component with props
      function Greeting(props) {
        return (
          <h1>
            Hello, {props.firstName}
          </h1>
        );
      }

      // custom props validator
      const PropTypes = {
        string(props, propName, componentName) {
          if (typeof props[propName] !== "string") {
            return new Error(
              `Hey, the component ${componentName} need the prop ${propName} to be a string, but you passed a ${typeof props[
                propName
              ]}.`
            );
          }
        }
      };

      // Using custom props validator
      Greeting.propTypes = {
        firstName: PropTypes.string
      };

      ReactDOM.render(<Greeting firstName="Bipin" />, rootElement);
    </script>
  </body>

Output

Passing Wrong Props Type

<body>
    <div id="root">This will be replace by React</div>

    <script src="https://unpkg.com/react@16.13.1/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.9.4/babel.js"></script>
    <script type="text/babel">
      const rootElement = document.getElementById("root");

      // functional component with props
      function Greeting(props) {
        return (
          <h1>
            Hello, {props.firstName}
          </h1>
        );
      }

      // Custom props type validator
      const PropTypes = {
        string(props, propName, componentName) {
          if (typeof props[propName] !== "string") {
            return new Error(
              `Hey, the component ${componentName} need the prop ${propName} to be a string, but you passed a ${typeof props[
                propName
              ]}.`
            );
          }
        }
      };

      // Using custom props validator
      Greeting.propTypes = {
        firstName: PropTypes.string
      };

      ReactDOM.render(<Greeting firstName={123} />, rootElement);
    </script>
</body>

Output

In the console, you can see that there is a warning:
⚠️ Failed prop type: ...

Using NPM Packing called PropTypes for props Validation

To use the PropTypes package we have to add the script given below after the babel.js script.

<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>

Example

<body>
    <div id="root">This will be replace by React</div>

    <script src="https://unpkg.com/react@16.13.1/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.9.4/babel.js"></script>
    <script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
    <script type="text/babel">
      const rootElement = document.getElementById("root");

      // functional component with props
      function Greeting(props) {
        return (
          <h1>
            Hello, {props.firstName} {props.lastName}
          </h1>
        );
      }

      // Using npm package called PropTypes to validate the props
      Greeting.propTypes = {
        firstName: PropTypes.string
      };

      ReactDOM.render(<Greeting firstName="Bipin" />, rootElement);
    </script>
</body>

Output

Passing Wrong Prop Type

<body>
    <div id="root">This will be replace by React</div>

    <script src="https://unpkg.com/react@16.13.1/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.9.4/babel.js"></script>
    <script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
    <script type="text/babel">
      const rootElement = document.getElementById("root");

      // functional component with props
      function Greeting(props) {
        return (
          <h1>
            Hello, {props.firstName}
          </h1>
        );
      }

      // Using npm package called PropTypes to validate the props
      Greeting.propTypes = {
        firstName: PropTypes.string
      };

      ReactDOM.render(<Greeting firstName={123} />, rootElement);
    </script>
</body>

Output

In the console, you can see that there is a warning:
⚠️ Failed prop type: ...

Requiring Props

 <body>
    <div id="root">This will be replace by React</div>

    <script src="https://unpkg.com/react@16.13.1/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone@7.9.4/babel.js"></script>
    <script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
    <script type="text/babel">
      const rootElement = document.getElementById("root");

      // functional component with props
      function Greeting(props) {
        return (
          <h1>
            Hello, {props.firstName}
          </h1>
        );
      }

      // Using npm package called PropTypes to validate the props
      Greeting.propTypes = {
        firstName: PropTypes.string.isRequired
      };

      ReactDOM.render(<Greeting />, rootElement);
    </script>
</body>

Output

In the console, you can see that there is a warning:
⚠️ Failed prop type: ...

Note: For the Performance reasons propTypes is only checked in development mode.

In the code given below, we are not passing firstName prop.

<body>
    <div id="root">This will be replace by React</div>

    <!-- using react.production.min.js -->
    <script src="https://unpkg.com/react@16.13.1/umd/react.production.min.js"></script>

    <!-- using react-dom.production.min.js -->
    <script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.production.min.js"></script>

    <script src="https://unpkg.com/@babel/standalone@7.9.4/babel.js"></script>
    <script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>

    <script type="text/babel">
      const rootElement = document.getElementById("root");

      // functional component with props
      function Greeting(props) {
        return <h1>Hello, {props.firstName}</h1>;
      }

      // Using third party package called PropTypes to validate the props
      Greeting.propTypes = {
        firstName: PropTypes.string.isRequired
      };

      ReactDOM.render(<Greeting/>, rootElement);
    </script>
</body>

Output

In the output, you can see that there no warning in the console.

Top comments (0)