Ad

Ensuring Each Element Of An Array Property Conforms To Custom Shape In React

- 1 answer

I want to ensure every element of an array property conforms to a particular shape.

This is different than the question answered in React proptype array with shape. They tested if every element matched a given pre-defined React proptype validator, in that case React.propTypes.number. I'm interested testing against a custom object shape.

For example:

class MyClass extends React.Component {
  constructor(props) {
    super(props);
  }

  static propTypes = {
    data: React.PropTypes.arrayOf({
      name: React.PropTypes.string,
      year: React.PropTypes.number,
    })
  }
}

This triggers a warning: Failed propType: typeChecker is not a function Check the render method

Ad

Answer

You're close, but you need to specify what kind of proptype the array is of, and React.PropTypes.shape let's you specify an object with keys and their types.

static propTypes = {
  data: React.PropTypes.arrayOf(
    React.PropTypes.shape({
      name: React.PropTypes.string,
      year: React.PropTypes.number,
    })
  )
}

tip: do import React, { PropTypes } from 'react' so you can just use PropTypes.

Ad
source: stackoverflow.com
Ad