Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Create a Home Layout Component with a GraphQL Query in Gatsby


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: 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."

    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.

    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.

    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.

    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.

    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.

    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.

    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.