Let’s say I have the following React component in Typescript:
type FooProps = React.PropsWithChildren<{}>;
export function Foo({ children }: FooProps) {
return <div>{children}</div>;
}
A lot of React libraries declare components of <Foo.Bar> type, allowing you to write the following:
<Foo>
<Foo.Bar></Foo.Bar>
<Foo.Bar></Foo.Bar>
<Foo.Bar></Foo.Bar>
</Foo>
I think this is pretty nice to write, but how can I implement the same with a custom component?
I looked at the implementation in some libraries and I saw that <Foo> is actually implemented like
export const Foo = ... & {
Bar: typeof Bar
}
I tried to write the following, but without success.
>Solution :
I have an example for you:
All you need is define a subsection to your Root component with RootComponent.WhateverYouNeed = Component
type FooProps = React.PropsWithChildren<{ testId: string }>;
const Root = () => {
return <div></div>;
};
const Foo = (props: FooProps) => {
return <div data-testid={props.testId}>foo</div>;
};
const Bar = (props: { testId: string }) => {
return <div data-testid={props.testId}>bar</div>;
};
Root.Foo = Foo;
Root.Bar = Bar;
export default function App() {
return (
<div>
<Root />
<Root.Bar testId="test" />
<Root.Foo testId="test" />
</div>
);
}