How to Add Prop Type Validation with PropTypes to a Functional Stateless React Component?

Sometimes, we want to add prop type validation with PropTypes to a functional stateless React component.

In this article, we’ll look at how to add prop type validation with PropTypes to a functional stateless React component.

Add Prop Type Validation with PropTypes to a Functional Stateless React Component

To add prop type validation with PropTypes to a functional stateless React component, we can set the propRTypes property of the functional stateless component to an object that has the prop names as the keys and the corresponding prop data types as the values.

For example, we write:

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

const Header = ({ name }) => <div>hi {name}</div>;

Header.propTypes = {
  name: PropTypes.string
};

Header.defaultProps = {
  name: "james"
};

export default function App() {
  return (
    <>
      <Header />
    </>
  );
}

We create the Header component that takes the name prop.

And we validate the data type of the name prop with:

Header.propTypes = {
  name: PropTypes.string
};

We make React check that name should be a string with the object above.

And then we set the default value of name with:

Header.defaultProps = {
  name: "james"
};

We set the default value of name to 'james'.

Therefore, since we passed nothing for name in App, we see ‘hi james’ displayed.

Conclusion

To add prop type validation with PropTypes to a functional stateless React component, we can set the propRTypes property of the functional stateless component to an object that has the prop names as the keys and the corresponding prop data types as the values.