Catching bugs in React with PropType Validation

sanderdebr

sanderdebr

Posted on March 17, 2020

Catching bugs in React with PropType Validation

TypeScript, which is a superset of JavaScript that compiles down to plain JavaScript, is immensely popular. Actually it even has more npm package downloads than the React library:

typescript vs react

One of the main benefits of TypeScript is typechecking, which can avoid painful bugs. In this article I want to show you that you do not always need to use TypeScript to typecheck your application because React has some built-in typechecking abilities.


Setting up the component

First of all, I would like to recommend you to use the Visual Studio code extension for ES7 snippets called: ES7 React/Redux/React-Native/JS snippets.

After installing the extension, create a new JS file inside your React application and just type rafcp inside the file and press enter. This will create the basic component with PropTypes included and also give it the name of the filename you just gave it. Using the extension saves you so much time setting up boilerplate components.

Next up I would like to advise you to use the Prettier extension if you do not have it already so you do not have to worry about spacing and structuring your code.

Now select the name of your component and press CTRL+D a couple times and see what this does. It will select the other selected words and create multiple cursors. Another great way to improve your workflow! Let's change all three texts to UserProfile and destructure off the props, which is a name object with two properties:

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

const UserProfile = ({ user: { name, likes } }) => {
  return <div>Hi, {name}!</div>;
};

UserProfile.propTypes = {};

export default UserProfile;


Adding propTypes

With the propTypes we can make sure the data we are receiving is valid.
In this example, we are receiving an object, a string and a number type.

Go into your propTypes object and type in name: and then ptsr and press enter. This is a shortcut to add a propType for a string which is required. The same you can do for number: ptnr. Easy, right!

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

const UserProfile = ({ user: { name, likes } }) => {
  return <div>Hi, {name}!</div>;
};

UserProfile.propTypes = {
  name: PropTypes.string.isRequired,
  likes: PropTypes.number.isRequired
};

export default UserProfile;

You can check all the types and read up on this topic more at the official React documentation

đź’– đź’Ş đź™… đźš©
sanderdebr
sanderdebr

Posted on March 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related