React.PropTypes Is Dead, Long Live PropTypes

Casey A. Childers

tl;dr As of React v15.5 PropTypes are deprecated in the React package and have been given a package of their own.

🍂 Change is an inevitable part of life.

The upshot is twofold. 1) If you use another type-checking mechanism, you don’t have to worry about shipping unnecessary bulk to your end users. Omit the import and bank the weight loss. 2) Your PropType declarations are going to be more svelte than you ever thought possible.

The downside is that if you’ve been ignoring deprecation warnings about calling PropTypes directly since v15.3 (no judgement), that chicken has come home to roost.

Let’s get into it, but first you’ll need to install the package in your project.

$ npm install prop-types --save

Or, you know, do the Yarn thing. Either way here’s your old simple component with validation:

import React from 'react';

function Detail ({caption, style}) {
  return <p style={style}>{caption}</p>
}

Detail.propTypes = {
  caption: React.PropTypes.string.isRequired,
  style: React.PropTypes.objectOf(
    React.PropTypes.string
  ),
}

export default Detail;

And here it is the new way:

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

function Detail ({caption, style}) {
  return <p style={style}>{caption}</p>
}

Detail.propTypes = {
  caption: PropTypes.string.isRequired,
  style: PropTypes.objectOf(
    PropTypes.string
  ),
}

export default Detail;

Actually, scratch that. We promised svelte; so give it a destructured spin like so:

import React from 'react';
import {string, objectOf} from 'prop-types';

function Detail ({caption, style}) {
  return <p style={style}>{caption}</p>
}

Detail.propTypes = {
  caption: string.isRequired,
  style: objectOf(
    string
  ),
}

export default Detail;

That, dear friends, is pretty as a picture, and the good news is it all works precisely like you’re used to. Warnings in development. Silence in production.

The only notable exception is the one we mentioned above: directly invoked PropTypes. Those checks will automatically call the following block in production:

var productionTypeChecker = function () {
  invariant(false, 'React.PropTypes type checking code is stripped in production.');
};

Throwing an error and breaking stuff. You’ll have to refactor those invocations in your code or work out your own fork of prop-types to keep them on the upgrade train.

👉 Whatever you do, don't sweat this change. It's a net gain with a mild inconvenience tax.

✖ Clear

🕵 Search Results

🔎 Searching...