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 in our site will have Navigation bar, Footer, etc.

II. How to create layout components

To create 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

├── 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 />
            <Footer />

export default layout

The content of other pages will be placed in {children}. 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 (
      <h2>Hello World</h2>

export default Home