Add a Shared Layout Component to a Gatsby Site

Laurie Barth
InstructorLaurie Barth

Share this video with your friends

Send Tweet
Published a year ago
Updated 10 months ago

Create a shared Layout component with semantic HTML to provide proper landmarks to the page. Additionally, use the Link component from the core Gatsby package to add a Homepage route to the header.

Instructor: [0:03] Create a folder in src called components. Inside that folder, create a file called layout.js. Import React from 'react' and create a new component. We'll call our component layout. For right now, it will only return a div. Make sure to export layout as the default export of this file.

[0:43] Inside our div, we're going to use Semantic HTML. We'll create a header tag with a nav inside of it.

[0:58] We'll import the link component from the Gatsby package. This allows us to create routes between pages within our project. We'll link to / which is home and use the appropriate text.

[1:23] We'll also add a main element. In order to do that, we want to pass children into our layout component and display those children inside main.

[1:38] Finally, we'll add a footer element. We'll put a paragraph inside and call it A fun footer.

[1:53] Once we've saved, we're going to use our layout. We'll import layout from the relative path in our index page, ../components/layout. Now we'll wrap our entire Hello World div in layout. Since we have more than one line in our component, we'll need to add parentheses as well.

[2:30] Now we can see that our page renders inside our layout. We can do the same for our 404 page. This way, when a user accidentally navigates to a page that they weren't meant to go to, they'll always be able to access home and go back to the main page.