skip to Main Content

I want to create a reusable components in my website. I have created a following components

const Header: React.FC = () => …
const Content: React.FC = () => …

const MyCustomComponent = {Header, Content};
export default MyCustomComponent;

From other components I can able to consume like below

import MyCustomComponent …
…
<MyCustomComponent.Header />
<MyCustomComponent.Content />

But my expectation is, those component should be wrapped like below

import MyCustomComponent …
…
<MyCustomComponent>
<MyCustomComponent.Header />
<MyCustomComponent.Content />
</MyCustomComponent>

My Goal is I can able to pass more children props to the wrapper as well. At the same time children component should be call under parent component.

Thanks in advance.

2

Answers


  1. Chosen as BEST ANSWER

    In React(>18) the following code works. Thanks for the support

    export const App = () => {
      return (
        <MyCustomComponent>
          <MyCustomComponent.Header>
                  Header Content
          </MyCustomComponent.Header>
    
          <MyCustomComponent.Footer>
                 Footer Content
          </MyCustomComponent.Footer>
        </MyCustomComponent>
      );
    };
    
    

    in MyCustomComponent.tsx

    const CustomHeader: FC<PropsWithChildren> = ({ children }) => {
        return (
            <div className='custom-header'>{children}</div>
        )
    };
    
    const CustomFooter: FC<PropsWithChildren> = ({ children }) => {
        return (
            <div className='custom-footer'>{children}</div>
        )
    };
    
    const MyCustomComponent: FC<PropsWithChildren> = ({children}) => {
       return children;
    });
    
    MyCustomComponent.Header = CustomHeader;
    
    MyCustomComponent.Footer = CustomFooter;
     
    
    export default MyCustomComponent; 
    

  2. There’s nothing that stops you from doing this:

    export default function App() {
      return (
        <MyCustomC>
          <MyCustomC.C1 />
          <MyCustomC.C2 />
          <SomeOther />
        </MyCustomC>
      );
    }
    
    export function MyCustomC({ children }) {
      return <div>{children}</div>;
    }
    
    export function C1() {
      return <div>111</div>;
    }
    
    export function C2() {
      return <div>222</div>;
    }
    
    export function SomeOther() {
      return <div>333</div>;
    }
    
    MyCustomC.C1 = C1;
    MyCustomC.C2 = C2;
    

    except that such usage of components is not documented anywhere and might have inconsistent behaviour.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search