13

Given this contrived example, what is the best definition of componentType?

const componentType = PropTypes.oneOfType([
    PropTypes.shape({render: PropTypes.func.isRequired}), // React.createClass / React.Component ...better way to describe?
    PropTypes.func,                                       // Stateless function
    // others?
]);

const Selector = React.createClass({

    propTypes: {
        components: PropTypes.arrayOf(componentType).isRequired,
        index:      PropTypes.number.isRequired,
    },

    render() {
        const Component = this.props.components[this.props.index];
        return (
            <Component />
        );
    }
});

PropTypes.node is not I'm looking for; its usage would look like this:

<Selector components={[<ThingA  />, <ThingB  />]} />

whereas I want something that would look like:

<Selector components={[ThingA, ThingB]} />

I want to pass types, not instances.

vsync
  • 118,978
  • 58
  • 307
  • 400
Jim Bolla
  • 8,265
  • 36
  • 54

4 Answers4

14

I crossposted to github and got this answer. So it should be:

const componentType = PropTypes.oneOfType([PropTypes.string, PropTypes.func])

func covers types from "classic" react components, ES6 classes, and stateless function components. string covers the native element case (eg "div").

Jim Bolla
  • 8,265
  • 36
  • 54
4

This seems to be most up to date: https://stackoverflow.com/a/55784547/4993912

TLDR;

const propTypes = {
    component: PropTypes.elementType,
    requiredComponent: PropTypes.elementType.isRequired,
};
madav
  • 2,918
  • 1
  • 13
  • 17
-1

youre looking for a combination of arrayOf and element. the list of propTypes can be found on the Reusable Components page of the docs.

I'd expect it would look something like this:

components: React.PropTypes.arrayOf(React.PropTypes.element)
PhilVarg
  • 4,762
  • 2
  • 19
  • 37
-1

This is how react-router handles it here:

import React from "react";
import { isValidElementType } from "react-is";

Route.propTypes = {
    children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),
    component: (props, propName) => {
      if (props[propName] && !isValidElementType(props[propName])) {
        return new Error(
          `Invalid prop 'component' supplied to 'Route': the prop is not a valid React component`
        );
      }
    },
    exact: PropTypes.bool,
    location: PropTypes.object,
    path: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.arrayOf(PropTypes.string)
    ]),
    render: PropTypes.func,
    sensitive: PropTypes.bool,
    strict: PropTypes.bool
  };
Zack Knopp
  • 2,765
  • 2
  • 13
  • 14