Reputation: 3225
I have a component that I wish to accept another component as a prop, and render that. I wish for that passed component to be optional, and render nothing in that case.
The following code works perfectly:
const Component = ({ Inner }) => (
<div style={{ borderStyle: "solid" }}>
<Inner />
</div>
);
Component.propTypes = {
Inner: PropTypes.element
};
Component.defaultProps = {
Inner: () => null
};
However, on the first load of the page, prop-types
complains:
Warning: Failed prop type: Invalid prop
Inner
of typefunction
supplied toComponent
, expected a single ReactElement.
My current solution is to redefine the propType
as PropTypes.oneOfType([PropTypes.element, PropTypes.func])
, but this seems entirely incorrect.
What should my propType
or defaultProp
actually be?
This question is similar to If proptype of element what is the default?, but that has accepted an answer that doesn't work, and even if it did, it's not a great deal of help to me, as I'm using react native for real. I've not framed the question in a manner pertaining to react native, as like I said, my example works, it's just prop-types
being a big meanie.
Upvotes: 2
Views: 667
Reputation: 184
Using the type of elementType will resolve your problem.
Component.propTypes = {
Inner: PropTypes.elementType
};
Since your prop is a react component thus we use elementType. If you ever open the source code for the prop-types you will find this there.
Hope so this is helpful to you.
Upvotes: 4