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

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:

  1. to exist
  2. 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:

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

(Again, first import PropTypes else you will be upset…)

Other Uses of Proptypes

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!



All about the things I bumble into as a Web Dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store