X

Creating a layout in Gatsby with VSCode

WordpresstoGatsby

We have our footer and header together and it’s time to talk about Layout. We can create a layout component in Gatsby such that our header and footer can be embedded/nested into any page you wish to have later on. Example our about, contact pages. This will allow us to clean up some of our page code.

Creating a layout in Gatsby with VSCode

We will create a component called component/layout.js inside the component folder. The code for layout is as below.

import React from "react"
import Header from "./header"
import Footer from "./footer"

const Layout = ({children}) => (
{children}
) export default Layout

Couple of things you may notice, we are taking something called children into the parameter of the Layout component. This is a way for us to embed/nest more html components inside the layout. If we look at our example pages/index.js page we will see everything that is declared inside out page will be translated into children for the layout page. Thus having a header and footer page for them also. We have embedded content and sidebar div into the layout, which will result in Header and Footer to wrap them around, with the code below.

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

export default function Home() {
  
  return (
    
      
Content goes here
Sidebar goes here
) }

Now our page will look like the image below.

Header Footer with sidebar and content page

There are still couple of things to fix but we are getting there, and you may have notice that the data is being repeated in our layout. I think we can do better and Gatsby does allow us to do better with StaticQuery which we will cover next.

Summary

We talked about using layout component for our content so that we can use nested components for other pages. We have used the children parameter to pass in nested html components into our layout component so that we can embed other content into our page.

Categories: Gatsby VSCode
Tags: gatsbyvscode
Taswar Bhatti:
Related Post