React PropTypes: Allow different types of PropTypes for one prop

ReactjsReact Proptypes

Reactjs Problem Overview


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
}

Reactjs Solutions


Solution 1 - Reactjs

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

Learn more: Typechecking With PropTypes

Solution 2 - Reactjs

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

size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),

Solution 3 - Reactjs

This might work for you:

height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

Solution 4 - Reactjs

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;

Solution 5 - Reactjs

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin AmiranoffView Question on Stackoverflow
Solution 1 - ReactjsPaweł AndruszkówView Answer on Stackoverflow
Solution 2 - ReactjscleongView Answer on Stackoverflow
Solution 3 - ReactjsCorrinaBView Answer on Stackoverflow
Solution 4 - ReactjsSourav SinghView Answer on Stackoverflow
Solution 5 - ReactjsMichaelView Answer on Stackoverflow