React propTypes: objectOf vs shape?

What is the difference between PropTypes.objectOfand PropTypes.shape? In docs :

  // An object with property values of a certain type
  optionalObjectOf: PropTypes.objectOf(PropTypes.number)

vs

    // An object taking on a particular shape
    optionalObjectWithShape: PropTypes.shape({
      color: PropTypes.string,
      fontSize: PropTypes.number
    })

When to use objectOfand when to use shape?

+6
source share
2 answers

PropTypes.objectOf used to describe an object whose properties are all of the same type.

PropTypes.shape used to describe an object whose keys are known in advance and can represent different types.

+11
source

Just wanted to provide an example given the following object:

{
    petStore: {
        animals: {
           '23': { name: 'Snuffles', type: 'dog', age 13 }
           '29': { name: 'Mittens', type: 'cat', age: 7 }
        }
    }
}

ObjectOf and form

Used when an object can have different property names, but a consistent set of properties for each of them:

const animalItemShape = {
    name: PropTypes.string,
    type: PropTypes.string,
    age: PropTypes.number
}

const petStoreShape = {
    animals: PropTypes.objectOf(PropTypes.shape(animalItemShape))
}

, animals - , , animalItemShape.

, !

+8

All Articles