Tutorial

Working With Types Using React.PropType

React

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

As compilation (er…transpilation) becomes the defacto standard of the post ES5, JSX-leaning JS dev landscape—care of tools like Babel—there is a growing sentiment that it may be time to let go of our fair language’s dynamic and coercive ways in favor of a more sensible, statically-typed way of doing things.

Which leads to questions like, “Sure, but where do I even start?”

The biggest camps are TypeScript (Microsoft) and Flow (Facebook), but if you’re working in React you’ve already got a wonderful, low-maintenance alternative in your codebase that’s as easy to implement as it is to learn.

import React, { PropTypes } from 'react';

Say hello to React.PropTypes, a developer-friendly tool for declaring and checking types. Sure, it handles all the primitives ( array, bool, func, number, object, string, symbol) easily enough:

function Nest({name}) {
  return (
    <div>
      We called it {name}.
    </div>
  );
}

Nest.propTypes = {
  name: PropTypes.string,
}

export default Nest;

But there’s also enough depth under the hood to manage some pretty sophisticated verifications:

Nest.propTypes = {
  name: PropTypes.string,
  eggs: PropTypes.shape({
    species: PropTypes.string,
    femaleToMale: PropTypes.arrayOf(PropTypes.number),
    hobbies: PropTypes.oneOf(['swimming', 'stalking']),
  }),
}

All-in you get nine additional types to throw your props against:

  • node and element for all your DOM and React element needs
  • instanceOf for digging into prototypes
  • oneOf for lists of known potential values
  • oneOfType for lists of known potential types
  • arrayOf and objectOf for arrays and objects composed of a single type
  • shape for objects in the shape of a specific schema
  • and any for when you really don’t want to check for a type

Furthermore, you can attach isRequired to any PropType declaration for added rigidity.

hobbies: PropTypes.oneOf(['swimming', 'stalking']).isRequired

Couple things to note, PropType checking is disabled in production, and it’s only present as a guiding hand in development mode. It throws warnings, not errors.

A missing required prop warning in the Chrome console

👉 That’s it. You’re a type checking expert now. Don’t abuse this new power in opinion convos.

0 Comments

Creative Commons License