⚠️ This lesson is retired and might contain outdated information.

Add Custom propType Validation to React Components

Joe Maddalone
InstructorJoe Maddalone
Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 2 years ago

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

[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.

Vipulsharm
Vipulsharm
~ 7 years ago

Title.propTypes = { text(props, propName, component){ console.log(props, propName, component); } }

-- It's getting consoled twice.. is it always the case ? Any specifics ?

Markdown supported.
Become a member to join the discussionEnroll Today