React Pattern: Centralized PropTypes

Cory House:

In real apps with large objects, using PropTypes quickly leads to a lot of code. That’s a problem, because in React, you’ll often pass the same object to multiple components. Repeating these details in multiple component files breaks the DRY principle (don’t repeat yourself). Repeating yourself creates a maintenance problem. The solution? Centralize your PropTypes.

Using the shape function of the prop-types package it’s possible to define types yourself. You could have your own definitions an address or a user for example. These type definitions can then be used like other prop-types types.

Cory centralizes his (custom) PropTypes in types/index.js

import { shape, number, string, oneOf } from 'prop-types';

export const addressType = shape({
    id: number.isRequired,
    street: string.isRequired,
    street2: string,
    city: string.isRequired,
    state: string.isRequired,
    postal: number.isRequired,
});

export const userType = shape({
  id: number,
  firstName: string.isRequired,
  lastName: string.isRequired,
  company: string,
  role: oneOf(['user', 'author']),
  address: addressType.isRequired,
});

… and then imports them when needed:

import React, { Component } from 'react';
import {userType} from './../types';

export default class User extends Component {
  static propTypes = {
    user: userType.isRequired,
  };

  // …
}

React Pattern: Centralized PropTypes →

Elsewhere , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *