Home > database >  Reuse a component in other ones in React(AntDesign)?
Reuse a component in other ones in React(AntDesign)?

Time:09-21

I'm new to react so apologies for the basic question. I have a header component as below which I want to use in my other components


const { Header, Content, Footer, Sider } = Layout;


const NavHeader = (Components: any) => {
  const [collapsed, setCollapsed] = useState(true);
  
  return (
    <Layout>
      <Layout className="site-layout">
        <Header className="site-layout-background" style={{padding: 0,}}/>
        <Content>
            Content of the page
        </Content>
        <Footer>
          My Footer
        </Footer>
      </Layout>
    </Layout>
  );
};

export default NavHeader;

How can I reuse this code considering my pages should be placed inside the `<Content></Content>` part of the header?  

CodePudding user response:

You will want to pass a prop to the NavHeader component as a React.ReactElement, then you can display that in the content area. Here is a quick codesandbox example: https://codesandbox.io/s/pass-component-as-prop-9s070b?file=/src/NavHeader.tsx:28-226

interface Props {
content:React.ReactElement;
}

const NavHeader: React.FC:<Props> = ({content}) => {
  const [collapsed, setCollapsed] = useState(true);
  
  return (
    <Layout>
      <Layout className="site-layout">
        <Header className="site-layout-background" style={{padding: 0,}}/>
        <Content>
            {content}
        </Content>
        <Footer>
          My Footer
        </Footer>
      </Layout>
    </Layout>
  );
};

export default NavHeader;

Then to use the component:

<NavHeader content={<h1>Custom Component</h1>} />
  • Related