Blog>
Snippets

Creating a Layout Component

Demonstrate how to create a common layout component that wraps around the application's page content with a consistent header and footer across different pages.
import React from 'react';

// Header component
const Header = () => (
    <header>
        <h1>My App</h1>
        {/* Add other header elements here */}
    </header>
);

// Footer component
const Footer = () => (
    <footer>
        <p>Copyright © My Company 2023</p>
        {/* Add other footer elements here */}
    </footer>
);

// Layout component
const Layout = ({ children }) => (
    <div>
        <Header />
        <main>{children}</main>
        <Footer />
    </div>
);

export default Layout;
This code defines a functional Layout component using React, which includes a Header and a Footer component. Within the Layout, a 'children' prop is used to render the page content passed to it. This layout can be used to wrap around other page components to maintain a consistent structure across the application.
import React from 'react';
import Layout from './Layout'; // Import Layout component

// Example page component
const HomePage = () => (
  <Layout>
    <div>
      <h2>Welcome to the Home Page!</h2>
      {/* Page-specific content goes here */}
    </div>
  </Layout>
);

export default HomePage;
This code shows how to use the previously defined Layout component in a specific page component, like a home page. The page content is placed within the Layout tags, which will be passed as 'children' to the Layout component, thereby incorporating the common header and footer.