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.
To create layout component in Gatsby, we can follow the following steps:
/src
directorycomponents
directory/src/components
, create Layout.js
fileIn 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.
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