0

I have an array object being passed as props the array looks something like:

[
  {
    "title": "eat food"
  },
  {
    "title": "Drinks",
    "sub_items": [
      {
        "title": "Beer",
        "isDrinking": true
      }
    ]
  },
  {
    "title": "eat Pizza"
  },
  {
    "title": "Other Drinks",
    "sub_items": [
      {
        "title": "Soda",
        "isDrinking": false
      },
      {
        "title": "Soda",
        "isDrinking": false
      }
    ]
  }
]

What i want to do is add the propTypes validation, something like

title : PropTypes.string.isRequired

sub_items : PropTypes.array

sub_items : props validation inside the array such as title sting and isDrinking boolean.

note sure on how to achieve this on an array. (ps. my reactjs knowledge is very limited so excuse me if I am asking an obvious stupid question)

1

1 Answer 1

5

You can write:

PropTypes.arrayOf(PropTypes.shape({
  title: PropTypes.string.isRequired,
  sub_items: PropTypes.arrayOf(PropTypes.shape({
    title: PropTypes.string.isRequired,
    isDrinking: PropTypes.bool.isRequired
  })
})).isRequired

Notice how sub_items is not required, but if it is included in one of the objects, it has to be an array of objects with title and isDrinking defined.

Sign up to request clarification or add additional context in comments.

Comments

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.