Validate Custom React Component Props with PropTypes

Share this video with your friends

Send Tweet

When you create reusable React components, you want to make sure that people use them correctly. The best way to do this is to use TypeScript in your codebase to give you compile-time checking of your code. But if you’re not using TypeScript, you can still use PropTypes to get runtime validation. Between you and me, when I was still doing AngularJS work, I was so envious of this feature, that I tried to build it into AngularJS.

In this lesson we’ll learn how PropTypes work, why they’re not enabled in production, and how to use the pre-built prop-types package from the React team.

Michael
Michael
~ 5 years ago

Officially it seems that PropTypes are not recommended ? With flow or typescript instead recommended.

https://reactjs.org/docs/static-type-checking.html

Ian Jones
Ian Jones
~ 5 years ago

For larger code bases

I think TS and Flow are great but it adds a whole other layer of complexity so it's nice to have an option the check props without all that config.

AlexanderS Sadovsky
AlexanderS Sadovsky
~ 3 years ago

I prefer typescript over this. Never used this.

Kent C. Dodds
Kent C. Dodds(instructor)
~ 3 years ago

I prefer typescript over this. Never used this.

Same! If you're using typescript, don't bother with proptypes 👍

~ 7 months ago

If on production prop types are not applied, does it mean that props of incorrect type would be accepted on a production website? That sounds so weird to me!

Does it mean that in case when prop values are passed through user actions (e.g. user input), mechanisms other than the one shown in this video are recommended to catch errors like when someone provides a boolean into a "date of birth" field (try...catch?)