I'm building a component that requires its direct descendants to be at least one of two types of components (ValidChildA
or ValidChildB
).
Using the most upvoted comment on this answer, I came up with this solution:
const ValidChildA = () => <div></div>;
const ValidChildB = () => <div></div>;
const Parent: React.FC<ParentProps> = ({ children, ...passedProps }) => {
React.Children.forEach(children, child => {
const isValidChildA = child.type.prototype instanceof ValidChildA;
const isValidChildB = child.type.prototype instanceof ValidChildB;
console.log(isValidChildA, isValidChildB); // Outputs false every time.
if(!isValidChildA && !isValidChildB){
console.error("Parent component expects only ValidChildA or ValidChildB as direct children.");
}
});
return <div {...passedProps} />
};
export default function Page(){
return (
<Parent>
<ValidChildA />
<ValidChildB />
</Parent>
);
};
Now despite the children being valid, my error is still thrown and thus the component doesn't render correctly.
I could use the displayName
property to check if a child is a valid component, but since Next
uglifies the code and the displayName
property in production, this would break the app.