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 →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.