Layout components are for sections of your site that you want to share across multiple pages. For example, Gatsby sites will commonly have a layout component with a shared header and footer. Other common things to add to layouts are a sidebar and/or navigation menu. On this page for example, the header at the top is part of gatsbyjs.org’s layout component.
It is recommended to create your layout components alongside the rest of your components (e.g. into src/components/
).
In our example, we'll move all of the navigation to the layout component like so:
import React from 'react'
import { Link } from 'gatsby'
import { logout, isLoggedIn } from '../services/auth'
const Layout = ({ children }) => {
return (
<div>
<h1>Gatsby Pokedex!</h1>
{isLoggedIn() && (
<button onClick={() => logout(() => {})}>
Logout
</button>
)}
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/app/profile">Profile</Link>
</li>
<li>
<Link to="/app/stats">Stats</Link>
</li>
<li>
<Link to="pokemons">Pokemons</Link>
</li>
</ul>
{children}
</div>
)
}
export default Layout
Instructor: [0:00] In our React app, as you can see here, the navigation is always present in every page, but if we go back to our Gatsby page and go for Gumball and Pokémons, you can see that we're missing some navigation.
[0:22] To fix that, we need to use a layout component into Gatsby. Let's go to src and create a new folder, call it components. Inside of that, let's define a file called layout.js.
[0:47] In here, let's import React and define the component. Here, the component would receive the children that's exported. Let's go to our index. In here, we will basically get pretty much everything inside of this app. Let's get this div, copy it, and then here, let's return our div.
[1:43] Then at the end here, we'll display the children. To fix that also, let's go to index and import both of these elements. Hit save, and then in the index page, let's remove everything and keep the h2. You can also delete it from here.
[2:26] Before we save, you can see here we only see the main app. That's because we need to import the layout from components layout and wrap everything into layout. Hit save. You can see here we have our Gatsby app and then the navigation.
[2:54] Let's go to About. You can see we're still missing that navigation. We can simply go to the About page, and wrap everything in layout. Here, let's import layout from components layout, and door turn statement. Hit save. You can see here we have the About page.
[3:20] Same thing for Pokémons. Let's go to the main page of Pokémons and import layout in the bracket.