Typechecking with React PropTypes

Image for post
Image for post

An important part of developing is maintaining code clarity and minimizing errors. On larger projects and when many developers are involved, this can become challenging. JavaScript has seen very popular implementations for solutions such as TypeScript, a superset of JavaScript which ensures that tries to minimize errors with a type system. And just like TypeScript, React offers their own kind of typechecking in the form of outlines that store information on the kinds of data types a given component’s props should be, a prop’s data type.

Although React propTypes are a part of the React library, they are accessed via their own package, for optional use. To begin using them you have to install it into the project. So:

npm install --save prop-types

Afterwards, you can begin using the package by importing it into the module.

import PropTypes from 'prop-types';

Inside the module, after the defined class/functional based component and outside their code block, you outline the data types for the component’s props. You do this like so:

import React from 'react';
import PropTypes from 'prop-types';

As you can see, after defining the Person component, the propTypes were defined. Each propType was defined as a key value pair on the propTypes property. The “name” prop was assigned a “string” data type using the “PropTypes” object import on line 2 of the code above, and so on. There are many more propTypes that can be used like for example array, func, object and so on. You can also require that a component receives a specific prop by chaining onto the propType. Like so:

Person.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
isDeveloper: PropTypes.bool
};

In the code above, the “name” prop was made required to be passed to the Person component. In addition, you can also set default values for a component’s props in case it is not passed. Like so:

Person.defaultProps = {
age: 0,
isDeveloper: false
};

With this in place, the Person component can still return some information if the “age” or “isDeveloper” prop are not passed to it.

Overall, implementing these few changes can help prevent errors and ensure an easier experience for developers by cutting down on the time it takes to review the code base to become familiar with the various props and components. As always, to learn more, I recommend giving React’s documentation a look.

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

Flatiron School alumni and Full Stack web developer.

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