What are PropTypes and why do we use them

Jackattack
Level Up Coding
Published in
6 min readApr 5, 2020

--

By jackattack

In React, we pass data to our React components as props, whether it be from another component or from the Redux store or from anywhere else. The movement of data between or among these compartmentalized and modular entities is what makes React so compelling and efficient to me. React can be used to seamlessly spin up sophisticated webs of data that flow and transform throughout a program’s course. However, an application’s complex structure can just as seamlessly unravel and devolve into utter chaos and darkness. One of the most helpful ways I’ve recently found to debug and manage data flow in React has been with the use of PropTypes.

The ‘prop-types’ library is used to type check data as it moves into a component. PropTypes can help us debug our code more efficiently and ensure that our code is squeaky clean before deployment.

With the prop-types library, you can type check props for a multitude of characteristics, including but not limited to everything from our props’ data type down to the very keys and values of an object prop. Such an example that showcases a few of them are demonstrated below where I’ve created a hypothetical component called Example and assigned to it a property called propTypes, which I then set equal to an object. That object contains the props as keys, validating that each prop is both present and contain value(s) align with what is provided to the propTypes object, whether they a Boolean (bool), an object, a number, a string, a function (func), etc.

To elicit the usefulness of prop-types, I’ve drawn up a super simple, little react app and fetched data from the classic Poke API.

Stunning, right?

In this app, we can infinitely carousel through the first 40 Pokemon, displaying their names, their type indicated by the color of the circle, special moves, and a little image sprite. Here’s the source code below for our App component:

On this first page, in our App functional component we’re fetching the Pokemon data and using React hooks setting the state of allPoke with the useState hook and fetching our data in the useEffect hook. We then pass down our array of Pokemon stored in the variable allPoke as a prop to the Pokecards component.

In the PokeCards component, we have an index set equal to zero in our state and use the index state to send an individual Pokemon from our allPoke array down to the PokeCard. We also define functions, which we will invoke in the PokeCard component. In this component, we see our first instance of using the ‘prop-types’ library. On line two, we import the library and name it PropTypes. The prop-types library can now be used to type check our props as they are passed from component to component. On line 40, we give our component a property called propTypes and set it equal to an object that type checks each prop passed to our component. In this case, we are passing allPoke down to this component, and we want to make sure that its type is array and it is certainly required for the functioning so we give it the property isRequired.

I’m now going to break my app by setting the allPoke prop equal to an object instead of an array as isRequired by PropTypes. On Line 40, instead of passing down the allPoke array of Pokemon objects, I’m merely passing down an object. Here’s what we see in the browser console.

Look at all those errors! This successfully broke the app. If we take a closer look at the first error, we see that it’s a warning that reads to us what has probably happened. “Warning: Failed prop type: Invalid prop `allPoke` of type `object` supplied to `PokeCards`, expected `array`. This error could not have been more helpful! It told us exactly which variable was set to the wrong data type, in which component the warning popped up, and what sort of data type was expected. Imagine how helpful this could be if this happened on a much larger more complicated app. Imagine this was a codebase into which you were just digging your heels.

The latter point demonstrates one of the other benefits of using PropTypes: Contextualization. One of the more difficult aspects of using React and looking at other React app codebases is the ability to understand another or many other developers’ component map. PropTypes can be used to indicate to other developers what sorts of data each prop in a component is meant to be thereby giving others an access point into the logic of data flow.

Here’s another very cool and useful prop-types property we can use to type check our code. The ‘exact’ property, when used on a PropTypes object, will warn us if extra properties are added to an object that contradicts the values declared in our PropTypes. Let’s say we decided to create an object that holds style properties we want to pass down from our PokeCards component to the PokeCard component. We could maybe define it in our state as such.

After passing it down as a prop from PokeCards to PokeCard, we could then check for these exact keys using PropType’s exact method.

As you can see, the PokeCard propTypes property checks for more than just our pokeAbilitiesStyle property. We also are checking that our pokemon prop is an object, that onForwardClick and onBackClick are functions, and that index is a number. We can inject this style object as the style of any of our JSX elements and it’ll apply the given styles! But let’s see what would happen if we were to add a key to our called color pokeAbilitiesStyles.

Our code does not break, and the blue color was in fact applied (*pokeAbilities style was applied to ‘chlorophyll’ and ‘overgrow’ just below the bulbasaur sprite), but look at the red warning error in our console. The error clearly indicates to us that an invalid key ‘color’ has been supplied to the pokeAbilitiesStyle prop, and that color is not in fact among our valid keys!

In Conclusion

PropTypes serves as a foil for the fundamental dispositions of the JavaScript language: the fact that JavaScript is a dynamically-typed language. When we declare variables in JavaScript or give assign function parameters, we do not need to assign them to a specific data type. However, with Swift (a framework I’ve been just beginning to pick up myself these days), which is statically-typed we declare a functions’ parameter’s datatypes along with the datatype of its return value before invoking the function.

NOT JAVASCRIPT

In the example above, we define a function called daysInQuarantine and give it the parameters name and days. In our function, we assign the data type required for each argument and if we had invoked daysInQuarantine and passed in different data types as arguments, it would yield an error. Although it requires much more typing, this certainly makes it easier to understand and contextualize our code than JavaScript might.

The ability PropTypes gives us to type check our react props is a helpful tool in debugging, data organization, and code contextualization. If you want even more information on PropTypes, I certainly recommend looking at React’s own documentation on PropTypes via the link provided below.

https://reactjs.org/docs/typechecking-with-proptypes.html

--

--