Skip to content

How to handle propTypes undefined in production #7031

@gajus

Description

@gajus

I am aware that:

Note that for performance reasons propTypes is only checked in development mode

https://facebook.github.io/react/docs/reusable-components.html#prop-validation

In development mode, we have "models": collections of propTypes, e.g.

import { PropTypes } from 'react';
import Layout from './../../component/Layout';

export const schema = {
    direction: Layout.propTypes.direction.isRequired,
    components: PropTypes.arrayOf(Component)
};

Layout is React component. I am expecting to access propTypes.direction property of Layout component. This works in development environment. However, because propTypes are stripped in production, I am getting an error:

Uncaught (in promise) TypeError: Cannot read property 'direction' of undefined(…)

The only fix that I can think of in user land is adding a safe-check that eliminates the dead-code during the build stage, e.g.

export const schema = __DEV__ ? {
    direction: Layout.propTypes.direction.isRequired,
    components: PropTypes.arrayOf(Component)
} : null;

This is sub-optimal, because it would require updating each instance where propTypes are used to declare data shapes.

  • Is there an environment variable that would force to keep propTypes but disable validation?
  • Can you suggest an alternative approach to this issue?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions