React PropTypes : Allow different types of PropTypes for one prop

Kevin Amiranoff picture Kevin Amiranoff · Jan 23, 2017 · Viewed 96k times · Source

I have a component that receives a prop for its size. The prop can be either a string or a number ex: "LARGE" or 17.

Can I let React.PropTypes know that this can be either one or the other in the propTypes validation?

If I don't specify the type I get a warning: prop type `size` is invalid; it must be a function, usually from React.PropTypes.

MyComponent.propTypes = {
    size: React.PropTypes
}

Answer

Paweł Andruszków picture Paweł Andruszków · Jan 23, 2017
size: PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]),

Learn more: Typechecking With PropTypes