Passing Proptypes.shape to Proptypes.arrayOf in react

Ankit picture Ankit · Jan 20, 2017 · Viewed 10.7k times · Source

I have created two models State and City in separate files. Importing City in the State.

State can have an array of Cities inside it.

The below code works fine.

State.js

let State = PropTypes.shape({
    name: React.PropTypes.string,
    cities: PropTypes.arrayOf(PropTypes.shape(City))
}); 

City.js

let City = PropTypes.shape({
    name: React.PropTypes.string,
    population: PropTypes.number
}); 

However, when i rewrite the cities as

let State = PropTypes.shape({
    name: React.PropTypes.string,
    cities: PropTypes.arrayOf(City)
}); 

it gives me warning.

Summary:

cities: PropTypes.arrayOf(PropTypes.shape(City)) works.

cities: PropTypes.arrayOf(City) doesn't.

It gives me following warning:

Warning: Failed propType: Property xx of component Xx has invalid PropType notation inside arrayOf. Check the render method of Yy.

My question is, City is a Proptypes.shape, then why do I need to mention Proptypes.shape(City) again in Proptypes.arrayOf?

Answer

Ken Gregory picture Ken Gregory · May 23, 2017

In your code:

let City = PropTypes.shape({
  name: React.PropTypes.string,
  population: PropTypes.number
}); 

What version of React are you using? You're referencing PropTypes from React.PropTypes and PropTypes. How are you importing PropTypes? Are you using the prop-types package?

I am using a similar scenario and it works for me. What does your render look like and what is the data provided for the prop?

For me, the following absolutely works:

cities: PropTypes.arrayOf(City)