Search code examples
arraysreactjsstringreact-proptypes

How to define PropTypes for Array<Object|string>


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


Solution

  • 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.