3

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?

1
  • Can you also show the related code? Commented Sep 23, 2019 at 8:02

2 Answers 2

1

This is a best practice that writes default props for your noun-required items, because of your warranty to your component that required props are passed to them.

So, in your case, remove redundant and unnecessary default props, then pass a default item to your default props like:

Example.defaultProps = {
   eItem: { 
      eList: [
         id: "Some default number",
         nameSurname: "Some default text",
         img: "default path for a placeholder item ",
      ] 
   },
};
Sign up to request clarification or add additional context in comments.

1 Comment

It isn't an empty array like that and I still see that eList is undefined in the console. By the way eList is an array, It's not an object.
0

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"}
],
}

3 Comments

Ok. This way force to give an initial value when I use this component but I don't want to define any eList prop when I use. I want to define a default value in the component if eList is undefined.
But now, eList has a one item and still comes undefined when initializing. I want to an empty array.
if you want empty to remove the isRequired you can add the number of the eList add what you need as[{id:10,nameSurname:"ddddfd",img:"mjjkjkjskdj"} ,{id:11,nameSurname:"mdmdmd",img:"mjjkjkjskdjdf"}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.