Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    React.PropTypes is deprecated in v15.5

    Add Custom propType Validation to React Components

    Joe MaddaloneJoe Maddalone
    0.14 - 16

    In addition to the types built into React.propTypes we can also define our own custom propType validator



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    In this example, our title component is expecting a prop of text which is not being passed in at its usage. We have a PropTypes setup for our component, which is expecting the text prop to be a PropType of string.

    We can tag on IsRequired in order to get our component to throw an error that the prop has not been provided, but that's about the extent of the built in validation that we can achieve.

    If we want to achieve further validation, we can instead of returning a React.PropTypes, we can return a custom function. This function is going to take in props, which is all the props that our components received, propName, which is the name for this particular prop, as well as our component.

    From there, if we wanted to achieve the required functionality, we can't just type on IsRequired, that's not going to work.

    To achieve the exact same functionality there, we can say, "if not propName in props," which would mean that the propName has not been provided, we can return a new error, we can just say, "missing propName." We can see that we're missing text, which is the propName.

    Now, if we provide that text equals the text, we can see we've gotten past that validation. If we want to validate further, let's say we're going to have a length required, we can say if props propName, that will get us the value for the text prop that was passed in. We'll say, if it's length is less than six, we're going to return a new error, we will say propName was too short.

    Save that, and we'll strip this guy down to just five characters. We should see our error message, that the text was too short, and if we go ahead and increase that to six or greater, our custom validation is passed.