Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

propType for accepting a component as a prop?

Tags:

reactjs

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.

like image 943
Jim Bolla Avatar asked Oct 12 '15 17:10

Jim Bolla


People also ask

How do you pass a component into a prop?

You can pass a component as props in React by using the built-in children prop. All elements you pass between the opening and closing tags of a component get assigned to the children prop. Copied!

What is the Proptype of a component?

Props and PropTypes are important mechanisms for passing read-only attributes between React components. React props, which stands for “properties,” are used to send data from one component to another. If a component receives the wrong type of props, it can lead to bugs and unexpected errors in your app.

Can I pass an object as a prop React?

Use the spread syntax (...) to pass an object as props to a React component, e.g. <Person {... obj} /> . The spread syntax will unpack all of the properties of the object and pass them as props to the specified component.


2 Answers

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").

like image 120
Jim Bolla Avatar answered Sep 22 '22 12:09

Jim Bolla


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

TLDR;

const propTypes = {
    component: PropTypes.elementType,
    requiredComponent: PropTypes.elementType.isRequired,
};
like image 22
madav Avatar answered Sep 23 '22 12:09

madav