⚠️ This lesson is retired and might contain outdated information.

Create a Home Layout Component with a GraphQL Query in Gatsby

Taylor Bell
InstructorTaylor Bell
Share this video with your friends

Social Share Links

Send Tweet

Starting with version 2 of Gatsby, a new StaticQuery component is available. This component allows you to make a GraphQL query and render the data it returns. In this lesson we will define a layout component that displays Header and Footer components with information from our site metadata.

Instructor: [00:00] I'm inside source/pages inside the "My blog" directory. If I do an LS, we can see the different posts that I've created and the index.js file. Let's open the index.js. We can see that we have a really basic component here that will render our "Hello world."

[00:18] Our "Hello world" component has been refactored to be called layout. In order to bring in data into our layout component, we'll import static query from Gatsby. Let's create a new component called header.

[00:30] Inside the return of header, we're going to return the static query component. One of the props that static query takes is our actual GraphQL query. I realize now that we need to import GraphQL also.

[00:43] Inside of our query to prop, we're going to pass in a tagged template, which is the syntax we use to make a GraphQL query. Our query syntax is GraphQL, then two backticks. Then we use the query keyword. We already know what our query looks like by looking at our GraphiQL.

[00:59] We know that we need site and siteMetadata. We want the title and description. The next prop that we pass to static query is what we want to render. In this case, we'll just render a simple proof of concept. We're going to pass a function that takes data, which comes from right here.

[01:15] We'll just return a div and it will go data.site.siteMetadata.title. Now we can replace "Hello world" with our header component. Now that we know we can get data from static query, let's create a new subcomponent to clean up this render a little bit.

[01:35] We'll create a new component called title and description. We'll destructure data from props. We'll pull our title and description from data. Inside our return, for now, we'll just do an h2 and a p tag.

[01:47] With our subcomponent created, we can now update the render prop of our static query component. Now we can see that our page has been updated. With the magic of editing, I've added some inline styles and our header is complete.