The prop-types library for React

Hi, in this post we are going to know the prop-types library that is created and maintained by the React developers.

So as we saw in this post React custom PropTypes we can create our own custom prop types (validations) but fortunately we have pre-build libraries that help us with those validations like the npm prop-types library.

So, if we have this code and the npm prop-type installed, then we can Validate the Message props like this using the string that means that the prop need to be string type and if we add the .isRequired this means that that prop is required in the Message custom component.

  // Validating the props of Message(function) with npm prop-types library
    Message.propTypes = {
      subject: PropTypes.string.isRequired,
      greeting: PropTypes.string.isRequired,
    }

Here the entire code:

    // React Custom component
    const Message = ({subject, greeting}) => {
      return (
        <div className="message">
          {greeting}, {subject}
        </div>
      )
    }

     // Validating the props of Message(function) with npm prop-types library
    Message.propTypes = {
      subject: PropTypes.string.isRequired,
      greeting: PropTypes.string.isRequired,
    }

    // Passing the props to Message and rendering
    const element = (
      <div className="container">
        <Message greeting="Hello" subject={10} />
      </div>
    )

Browser console result:

Note: if you are using TypeScript in your code then is just perfect validate just with TypeScript.

By Cristina Rojas.