Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    React.PropTypes is deprecated in v15.5

    Add Custom propType Validation to React Components

    Joe MaddaloneJoe Maddalone

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

    reactReact
    0.14 - 16
    Code

    Code

    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
    Transcript

    Transcript

    00:00 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.

    00:15 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.

    00:29 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.

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

    00:54 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.

    01:21 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.

    01:56 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.

    Discuss

    Discuss