Chapter 27 - 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.
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:
https://gist.github.com/f37beb3074e1470d4a3d2af1e158d391
Here we need:
props.name
to existprops.name
to 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:
https://gist.github.com/81dac1962088233d2b6f9a40119c7293
So now we have added a check which fails if we dont 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!
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...)
https://gist.github.com/5211a6d34ad3113936b93eabf2c9e3a2
This is just scratching the surface of proptypes. One useful proptye is shape
.
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.