Skip to content
Advertisement

Export default and multiple child components

I need the following component stucture:

import Layout from "./components/Layout";
<Layout>
   <Layout.Header>...</Layout.Header>
   <Layout.Body>...</Layout.Body>
   <Layout.Footer>...</Layout.Footer>
</Layout>

I tried to achieve this as follows:

import React from "react";

const Layout = (props) => {
  return <div className="layout">{props.children}</div>;
};

const Header = (props) => {
  return <header className="layout__header">{props.children}</header>;
};

const Body = (props) => {
  return <div className="layout__body">{props.children}</div>;
};

const Footer = (props) => {
  return <footer className="layout__footer">{props.children}</footer>;
};

export { Header, Body, Footer };
export default Layout;

But this does not seem to work. Can anybody tell me how to export these functions right so that I can use the above structure?

Advertisement

Answer

Thanks to this answer Using dot notation with functional component I found the solution is:

const Layout = (props) => {
  return <div className="layout layout--green">{props.children}</div>;
};

const Header = (props) => {
  return <header className="layout__header">{props.children}</header>;
};

const Body = (props) => {
  return <div className="layout__body">{props.children}</div>;
};

const Footer = (props) => {
  return <footer className="layout__footer">{props.children}</footer>;
};

Layout.Header = Header;
Layout.Body = Body;
Layout.Footer = Footer;

export default Layout;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement