React custom PropTypes

Hi, in this post we are going to lear how to create React custom PropTypes as part of React fundamental topic.

So here is the code, the const PropTypes = { object have our custom code that will validate our props.

    // React Custom prop validation
    const PropTypes = {
      string(props, propName, componentName) {
        const type = typeof props[propName]

        if (type !== 'string') {
          // This is going to be printed in the browser console
          return new Error(
            `The component ${componentName} needs the prop ${propName} to be string type`,
          )
        }
      },
    }

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

    // Validating the props of Message(function) with the PropTypes that we created at the top
    Message.propTypes = {
      subject: PropTypes.string,
      greeting: PropTypes.string,
    }

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

Nice, now if we insert a prop type number like this:

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

Then we are going to have the console error in the browser:

Is important validate our props because in that way we will keep our code more secure.

By Cristina Rojas.