The Beginner's Guide To React: Validation of Custom React Component Props with PropTypes
Tags: react, beginners, webdev
Published: 2020-04-04 04:39:10

React is a JavaScript library and JavaScript does not provide any type checking. You can use JavaScript extensions like **[Flow](https://flow.org/)** and **[TypeScript](https://www.typescriptlang.org/)** 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](https://www.npmjs.com/package/prop-types)** for props validation.

**Creating our own props validator**
```javascript
// 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``.

```javascript
// 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**
```html
 <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**
![](https://res.cloudinary.com/dqhskqqa6/image/upload/v1585927464/the-begineer%27s-guide-to-react/j4dl4fkzkwprbkji8wh5.png)

**Passing Wrong Props Type**
```html
<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**
![](https://res.cloudinary.com/dqhskqqa6/image/upload/v1585927368/the-begineer%27s-guide-to-react/uo32fyykziaqyskkwhqo.png)

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

# Using NPM Packing called **[PropTypes](https://www.npmjs.com/package/prop-types)** for props Validation

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

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

**Example**
```html
<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**
![](https://res.cloudinary.com/dqhskqqa6/image/upload/v1585927464/the-begineer%27s-guide-to-react/j4dl4fkzkwprbkji8wh5.png)

**Passing Wrong Prop Type**
```html
<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**
![](https://res.cloudinary.com/dqhskqqa6/image/upload/v1585927368/the-begineer%27s-guide-to-react/m168woervzsj9lbaahof.png)

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

**Requiring Props**
```html
 <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**
![](https://res.cloudinary.com/dqhskqqa6/image/upload/v1585927367/the-begineer%27s-guide-to-react/ay6t0kiahrsomdjfuj57.png)

In the console, you can see that there is a warning:
: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.

```html
<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**
![](https://res.cloudinary.com/dqhskqqa6/image/upload/v1585927464/the-begineer%27s-guide-to-react/j4dl4fkzkwprbkji8wh5.png)

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