Skip to content

Instantly share code, notes, and snippets.

@neosaurrrus
Created December 4, 2018 07:30
Show Gist options
  • Save neosaurrrus/deec8b394ee6da9ca3074b39e46065ca to your computer and use it in GitHub Desktop.
Save neosaurrrus/deec8b394ee6da9ca3074b39e46065ca to your computer and use it in GitHub Desktop.

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.

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:

https://gist.github.com/f37beb3074e1470d4a3d2af1e158d391

Here we need:

  1. props.name to exist
  2. props.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!

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

https://gist.github.com/5211a6d34ad3113936b93eabf2c9e3a2

Other Uses of Proptypes

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment