React propTypes: objectOf vs shape?

ReactjsReact Proptypes

Reactjs Problem Overview


What's the difference between PropTypes.objectOf and PropTypes.shape? In the PropTypes:

// 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 should I use objectOf and when should I use shape?

Reactjs Solutions


Solution 1 - Reactjs

PropTypes.objectOf is used when describing an object whose properties are all the same type.

    const objectOfProp = {
        latitude: 37.331706,
        longitude: -122.030783
    }
    // PropTypes.objectOf(PropTypes.number)

PropTypes.shape is used when describing an object whose keys are known ahead of time, and may represent different types.

    const shapeProp = {
        name: 'Jane',
        age: 25
    }
    // PropTypes.shape({ name: PropTypes.string, age: PropTypes.number })

Solution 2 - Reactjs

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 Shape

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

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

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

As you can see, animals is an object composed of multiple properties that each conform to the animalItemShape type.

Hope it helps!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDMac the DestroyerView Question on Stackoverflow
Solution 1 - ReactjsdjfdevView Answer on Stackoverflow
Solution 2 - ReactjsLevi FullerView Answer on Stackoverflow