Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create subsection of a component?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading