Z-Soroush
Z-Soroush

Reputation: 344

ReactJS: propTypes validation for array of objects

I have an array of objects

[
    {
      id: 1,
      customtitle: '',
      IconSRC: '',
      btnColor: '',
      inlineSyle: '',
      btnStyle: {
        width: '100px',
        height: '100px',
        flexDirection: 'column',

      },
      num: 1,
    },
    {
      id: 2,
      customtitle: '',
      IconSRC: '',
      btnColor: '',
      inlineSyle: '',
      btnStyle: {
        width: '100px',
        height: '100px',
        flexDirection: 'column',

      },
      num: 2,
    },]

and i confused to making it work as props validation .I need help to fix it, I try this way

Function.propTypes = {
  list: PropTypes.objectOf(PropTypes.shape({
    id: PropTypes.number,
    btnColor: PropTypes.string,
    customTitle: PropTypes.string,
    btnStyle:PropTypes.object
    IconSRC: PropTypes.string,
    inlineSyle: PropTypes.string,
  })),
};
Function.defaultProps = {
  List: [],
}; 

But that didn't work. without this proptypes my component works correctly. but eslint show an error with this text

.map' is missing in props validation eslint(react/prop-types)

Upvotes: 2

Views: 11318

Answers (2)

technicallynick
technicallynick

Reputation: 1592

What you want is actually PropTypes.arrayOf(). For example:

list: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.number,
    btnColor: PropTypes.string,
    customTitle: PropTypes.string,
    btnStyle:PropTypes.object
    IconSRC: PropTypes.string,
    inlineSyle: PropTypes.string,
  })),

You can see a full list of PropTypes here.

Upvotes: 11

developerKumar
developerKumar

Reputation: 1796

You can use it like:

Function.propTypes = {
  list: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.number,
    btnColor: PropTypes.string,
    customTitle: PropTypes.string,
    btnStyle:PropTypes.object
    IconSRC: PropTypes.string,
    inlineSyle: PropTypes.string,
  })),
};
Function.defaultProps = {
  List: [],
}; 

Also for more details about proptypes, visit Typechecking With PropTypes here

Upvotes: 2

Related Questions