I need to build a Wrapper for some other component and for that I try to filter React children by type:
// Component
const SubComponent = (props: SubComponentProps) => <NestedComponent {...props} />;
const MyComponent = (props: MyComponentProps) => {
const { children } = props;
const arrayChildren = React.Children.toArray(children);
// doesn't work, but the type is right (child.type === SubComponent)
const content = React.Children.count(arrayChildren) && arrayChildren.find((child) => React.isValidElement(child) && child.type === SubComponent);
// works, but the type complains (child.type.name === "SubComponent")
const content2 = React.Children.count(arrayChildren) && arrayChildren.find((child) => React.isValidElement(child) && child.type.name === "SubComponent");
return (
<Something {...props}>
{/* Type complains, but works */}
{content && <SomethingElse>{content.props.children}</SomethingElse>}
</Something>
);
};
MyComponent.SubComponent = SubComponent;
export default MyComponent;
// Usage
<MyComponent>
<MyComponent.SubComponent>
Some Stuff
</MyComponent.SubComponent>
</MyComponent>
Why doesn't child.type match?
And why doesn't child.type.name exist on the type, even though it works? (The type of the child is given as React.ReactChild | React.ReactFragment | React.ReactPortal)
Thanks!