Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React propTypes: objectOf vs shape?

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?

like image 245
DMac the Destroyer Avatar asked Aug 18 '17 20:08

DMac the Destroyer


People also ask

Is PropTypes deprecated?

As of React v15. 5 PropTypes are deprecated in the React package and have been given a package of their own. Change is an inevitable part of life.

Is PropTypes necessary in React?

One of the most important things when building React application is to make sure that the components receive correct props. Passing wrong props leads to bugs and unexpected behavior, so it's a good idea to warn developers about this as early as possible.

What is React PropType array with shape?

In this article we will learn how to use React PropType array with shape. We use React PropTypes for type checking of variables in react. It makes debugging much easier and quicker.

Can we use PropTypes in functional component?

Firstly, npm install / yarn add the prop-types package if you haven't already. Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.


2 Answers

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 })
like image 186
djfdev Avatar answered Nov 27 '22 04:11

djfdev


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!

like image 42
Levi Fuller Avatar answered Nov 27 '22 03:11

Levi Fuller