Quick Guide To React PropTypes

Quick Guide To React PropTypes

One of the problems associated with a growing application is the number of bugs that can be introduced into your code due to various reasons such as typographical errors, lack of typechecking, undefined methods, and a lot more. Today, we are going to learn how to prevent bugs in our code by including typechecking with PropTypes.

Props, short form for properties are a type of variable used to pass data/information to a component.

Before v15.5, we used React.PropTypes to include PropTypes in our apps but now we use the prop-types library as advised by React.

The prop-types library is a library used to check the types of props that are passed into a component against our expected types which we set using the library, it warns us if the types of props we pass aren't the same as what we expect. Some reasonable alternatives would be using Typescript or flow but they may be too complex for simple situations and this is where PropTypes shine.

To demonstrate PropTypes in action, we will be creating a movieCard component that renders details about a movie.

STEP ONE

We'll start by initializing our react app with create-react-app

npx create-react-app ptypes

We navigate to our src folder

cd src

Then we create our movieCard.js file

touch movieCard.js

STEP TWO

Install the PropTypes library so we can use it in our app.

npm install --save prop-types

STEP THREE

Now, we will implement our movieCard component and import PropTypes from the prop-types library

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

const MovieCard = () => {
    return ( 
        <div className='movie-card'>

        </div>
     );
}

Right now, our movieCard component returns just an empty div.

STEP FOUR

Next, we will destructure the props we expect that will be passed and flesh out our component.

...

const MovieCard = (
{
  name,
  description,
  ratings,
  starActors,
  genre,
  available,
}) => {
  return (
    <div className="movie-card">
      <h2>{name}</h2>
      <p>Description: {description}</p>
      <p>Ratings: {ratings} Stars</p>
      <h4>Actors:</h4>
      {starActors.map((actor) => (
      <p>{actor}</p>
      ))}
      <p>Genre:{genre}</p>
      {available ? <a href={`/${name}/watch`}>Watch Now</a> : <p>Not available</p>}
    </div>
  );
};

STEP FIVE

In this step, we would declare our proptypes so that our props can be compared against our expected types.

...
MovieCard.propTypes = {
  name: PropTypes.string,
  description: PropTypes.string,
  ratings: PropTypes.number,
  starActors: PropTypes.arrayOf(PropTypes.string),
  genre: PropTypes.oneOf(['Action', 'Adventure','Biography', 'Comedy','Drama','Fiction']),
  available: PropTypes.bool,
};

export default MovieCard;

Now that we have declared our proptypes, whenever we pass in a prop with the wrong type, a warning is thrown in the browser.

For example:

import React from 'react';
import './App.css';
import MovieCard from './movieCard';
function App() {
  return (
    <div className="App">
      <MovieCard
        name={99}
        description='Very cool movie about stuff'
        ratings='four'
        starActors={['Chimdia', 'Anyiam']}
        genre='Action'
        available={false}
      />
    </div>
  );
}

export default App;

In the code above, we pass in the name props is expected to be a string but we pass in a number. Similarly, the ratings props is expected to be a number but we pass in a string and although the code runs, we get the following error in the browser.

props-warn.JPG

From the warnings, we see that we pass in types that are different from what is expected and now we can make adjustments to make sure that the correct types are being passed to the component. There are different PropTypes validators and those for the basic data types are

  • PropTypes.any: As the name implies, can be of any data type
  • PropTypes.bool: Used when a Boolean value is expected
  • PropTypes.array: Used when an array is expected
  • PropTypes.func: Used when a function is expected
  • PropTypes.string: Used when a String is expected
  • PropTypes.number: Used when a Number is expected
  • PropTypes.symbol: Used when a symbol is expected
  • PropTypes.object: Used when an object is expected

These are the validators for the basic data types and more can be found Here

Conclusion

Using PropTypes is a good way to introduce typechecking into your react app as it relatively easier to set up and has little to no learning curve. Although it can't give you robust features that are included in Flow and TypeScript(a whole language), it can still help you prevent lots of unnecessary bugs.

Credits