React for Beginners #12 — Proptypes
We have used props a lot so far. They are pretty key to getting things to work well so it would be good to have some checks on what is getting passed.
This is what propTypes are for.
This is a very quick post about how to use them.
My First PropType
First of all if we want to use PropTypes we need to import it:
import PropTypes from "prop-types"
If you don’t do that, little will happen.
Right, lets take the following functional component as an example:
Here we need:
props.nameto be a string.
We can add a propType to a functional component by adding a property called propTypes to the Greeting object after we have defined it:
So now we have added a check which fails if we don’t pass in the prop or if it isnt a string. This produces a warning you can view in the console. Really handy if you are forgetful like me!
Adding a Proptype to a class-based component
You can add propTypes to a class based component. Whereas in a functional component we added a property afterwards. We can define our propType inside:
(Again, first import PropTypes else you will be upset…)
Other Uses of Proptypes
This is just scratching the surface of propTypes. One useful proptype is
shape which checks if an object takes a particular form.
We can always look at the React documentation to see all the other ways we can use propTypes.
One additional caveat is that when we eject into production we wont have them as they are a development tool.
To wrap up, I need to admit I don’t use them as much as I should. They seem like a damper on whatever component you are building to remember to stop and define propTypes. However, after encountering a number of bugs in my code that could have been easily spotted by using propTypes I am more inclined towards them going forward!