Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 831
Z-Soroush Avatar asked Jan 31 '26 03:01

Z-Soroush


2 Answers

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.

like image 119
technicallynick Avatar answered Feb 01 '26 18:02

technicallynick


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

like image 22
developerKumar Avatar answered Feb 01 '26 18:02

developerKumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!