Layout Components

I. What are layout components?

Layout components are for sections of your site that you want to share across multiple pages.

For example, every page on our site will have a Navigation bar, Footer, etc.

II. How to create layout components

To create a layout component in Gatsby, we can follow the following steps:

  • Navigate to to /src directory
  • Create a components directory
  • Inside the /src/components, create Layout.js file

In this example, we already have Navbar and Footer component.

src
├── components
│   ├── Footer.js
│   ├── Navbar.js
│   └── Layout.js

In /src/components/Layout.js

import React from "react"
import Navbar from "./Navbar"
import Footer from "./Footer"

const Layout = ({children}) => {
    return (
        <>
            <Navbar />
            {children}
            <Footer />
        </>
    )
}

export default Layout

The content of other pages will be placed in {children} props. In the example above, the content will be placed in the middle, after Navbar, and before Footer.

III. How to import and add layout components to pages

To apply a layout to a page, we need to import the Layout component and wrap the content of that page in it.

For example, in src/pages/index.js

import React from 'react'
import Layout from "../components/Layout"

const Home = () => {
  return (
    <Layout>
      <h2>Hello World</h2>
    </Layout>
  )
}

export default Home