How to define PropTypes for Array<Object|string>

Viewed 300

I have a prop named options which is an array with object or string. How can we use React PropTypes to define options? I just went through https://reactjs.org/docs/typechecking-with-proptypes.html

From PropTypes doc:

     // An array of a certain type
      optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

but how we can put string and object into PropTypes.arrayOf ? Thanks

1 Answers

To specify the propType for the options array that can have strings and objects, both at the same time, declare its PropType like this:

options: PropTypes.arrayOf(
    PropTypes.oneOfType([PropTypes.string, PropTypes.object])
  )

This will accept an all strings array, an all objects array or an array with strings and objects both.

Related