303

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
}
Penny Liu
  • 7,720
  • 5
  • 40
  • 66
Kevin Amiranoff
  • 9,811
  • 5
  • 36
  • 73

5 Answers5

695
size: PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.number
]),

Learn more: Typechecking With PropTypes

Beau Smith
  • 29,103
  • 12
  • 82
  • 88
Paweł Andruszków
  • 7,011
  • 1
  • 10
  • 10
31

For documentation purpose, it's better to list the string values that are legal:

size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),
cleong
  • 6,297
  • 2
  • 26
  • 38
13

This might work for you:

height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
jps
  • 11,454
  • 12
  • 42
  • 55
CorrinaB
  • 131
  • 1
  • 2
  • 2
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – rollstuhlfahrer Mar 09 '18 at 10:08
0

Here is pro example of using multi proptypes and single proptype.

import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';

class MyComponent extends Component {
  /**
   * Render
   */
  render() {
    const { title, data } = this.props;

    return (
      <>
        {title}
        <br />
        {data}
      </>
    );
  }
}

/**
 * Define component props
 */
MyComponent.propTypes = {
  data: oneOfType([array, string, shape({})]),
  title: string,
};

export default MyComponent;

Sourav Singh
  • 550
  • 4
  • 12
-5
import React from 'react';              <--as normal
import PropTypes from 'prop-types';     <--add this as a second line

    App.propTypes = {
        monkey: PropTypes.string,           <--omit "React."
        cat: PropTypes.number.isRequired    <--omit "React."
    };

    Wrong:  React.PropTypes.string
    Right:  PropTypes.string
Michael
  • 27
  • 1