Search code examples
reactjsreact-proptypes

React default props for array property in required object


I have an array as non-required property in required object and I want to give a default value for this array.

const { classes, eItem } = props;

eItem: PropTypes.shape({
   eList: PropTypes.arrayOf(PropTypes.shape({
      id: PropTypes.number.isRequired,
      nameSurname: PropTypes.string.isRequired,
      img: PropTypes.string,
   })),
}).isRequired,

Example.defaultProps = {
   eItem: { 
      eList: [] 
   },
};

I have written defaultProps like that, but I see that eList is undefined in the console.

How can I give a default value for eList as an empty array?


Solution

  • try this shape

    ReactComponent.propTypes={
      eItem:PropTypes.shape({
        eList: PropTypes.arrayOf(PropTypes.shape({
    
          id:PropTypes.number ,
          nameSurname: PropTypes.string,
          img: PropTypes.string
        }).isRequired
    
      })}
    

    with adding the defaultProps as this shape

    ReactComponent.defaultProps = {
      eItem: { 
      eList: [
    {id:10,nameSurname:"ddddfd",img:"mjjkjkjskdj"}
    ],
    }