Gatsby
Up and Running with Gatsby: Working with Data

Solution: Static Query

PRO

The solution to the static query assignment.

Okay, we've done the assignment on the page query, so let's make a static query by creating a footer component.

First, let's add the year to our siteMetadata in gatsby-config.js:

siteMetadata: {
    title: "Gatsby Thinkster",
    description: "Gatsby is awesome!",
    author: "Sam Julien",
    year: 2019,
  },

Then, create a new file in src/components called Footer.js. We'll import a few things up at the top:

import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import styled from "styled-components"

Now we can create our component with the static query:

export default () => {
  const data = useStaticQuery(graphql`
    query {
      site {
        siteMetadata {
          year
        }
      }
    }
  `)
}

And then use it in the component that we return:

  return (
    <div>
      <p>Copyright {data.site.siteMetadata.year}</p>
    </div>
  )

Let's also style our component:

const FooterText = styled.p`
  font-family: Verdana, Helvetica, sans-serif;
  font-size: 0.6rem;
  margin-left: 0.2rem;
`

Then, replace the p tag in the component with FooterText:

return (
    <div>
      <FooterText>Copyright {data.site.siteMetadata.year}</FooterText>
    </div>
  )

Finally, we need to use the Footer component inside of Layout.js:

export default ({ children, noHeader }) => (
  <Container>
    {!noHeader && <Header />}
    {children}
    <Footer />
  </Container>
)

Don't forget to import the component at the top of Layout.js if your editor doesn't do it for you:

import Footer from "./Footer"

And now you've got the hang of both page queries and static queries! Let's review what we've learned in this tutorial in the next video.

 

I finished! On to the next chapter