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.
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!
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.
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.
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").
This seems to be most up to date: https://stackoverflow.com/a/55784547/4993912
TLDR;
const propTypes = {
component: PropTypes.elementType,
requiredComponent: PropTypes.elementType.isRequired,
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With