React PropTypes - objectOf vs shape

React, Components, Proptypes · Jun 12, 2021

The prop-types package is used by millions of React developers every day in order to type check the props passed to their components. Most of us are probably familiar with a variety of its built-in validators, but many a developer seems to fall short when dealing with object props. Luckily, the PropTypes.objectOf() and PropTypes.shape() validators are here to help.

PropTypes.shape()

The PropTypes.shape() validator can be used when describing an object whose keys are known ahead of time, and may represent different types. For example:

import PropTypes from 'prop-types';
// Expected prop object - keys known ahead of time
const myProp = {
  name: 'John',
  surname: 'Smith',
  age: 27
};
// PropTypes validation for the prop object
MyComponent.propTypes = {
  myProp: PropTypes.shape({
    name: PropTypes.string,
    surname: PropTypes.string,
    age: PropTypes.number
  })
};

PropTypes.objectOf()

The PropTypes.objectOf() validator is used when describing an object whose keys might not be known ahead of time, and often represent the same type. For example:

import PropTypes from 'prop-types';
// Expected prop object - dynamic keys (i.e. user ids)
const myProp = {
  25891102: 'johnsmith',
  34712915: 'ducklord',
  76912999: 'mrquacks'
};
// PropTypes validation for the prop object
MyComponent.propTypes = {
  myProp: PropTypes.objectOf(PropTypes.number)
};

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • React useUpdate hook

    Forces the component to re-render when called.

    React, Components · Sep 24, 2021

  • Stateful checkbox with multiple selection

    Renders a checkbox list that uses a callback function to pass its selected value/values to the parent component.

    React, Components · Oct 13, 2021

  • Countdown timer

    Renders a countdown timer that prints a message when it reaches zero.

    React, Components · Oct 13, 2021