kylesimmonds
kylesimmonds

Reputation: 183

Is isRequired necessary for nested PropTypes?

Say I have this PropType defined:

Component.propTypes = {
  complicatedData: PropTypes.arrayOf(
    PropTypes.shape({
      name: PropTypes.string,
      data: PropTypes.arrayOf(PropTypes.number)
    })
  ).isRequired,
};

If that data structure is required, is the isRequired attributed necessary for every level of that nested structure, or does the top-level isRequired at the end encompass everything inside?

Upvotes: 1

Views: 1261

Answers (1)

Maokai
Maokai

Reputation: 372

The top level isRequired only checks if complicatedData is provided and is an array. You can give it an array with empty objects such as [{}, {}] and it'll pass the test based on your code.

If you want each element in your array complicatedData to have a name property, then you need to write:

Component.propTypes = {
  complicatedData: PropTypes.arrayOf(
    PropTypes.shape({
      name: PropTypes.string.isRequired,
      data: PropTypes.arrayOf(PropTypes.number)
    })
  ).isRequired,
};

Same if you want each element to have a data property.

Upvotes: 4

Related Questions