Gatsby
Up and Running with Gatsby: Taking Gatsby to Production

Using React Helmet

PRO

Let's add a title and description to our site.

In src/componentsLayout.js, we're going to use a static query to pull in the siteMetadata we created a while back. We'll then use that data to create a site title and meta description tag.

First, we'll import a few of things:

import React from "react"
import { Helmet } from "react-helmet"
import { useStaticQuery } from "gatsby"

Then, we'll build our static query inside of the component function:

// src/components/Layout.js
export default ({ children, noHeader }) => {
    const data = useStaticQuery(graphql`
        query {
          site {
          siteMetadata {
              title
              description
           }
          }
       }
    `)
        // ...
}

Next, we can create our Helmet:

<Helmet>
    <title>{data.site.siteMetadata.title}</title>
     <meta name="description" content={data.site.siteMetadata.description} />
</Helmet>

We need to be sure to wrap our Layout in a React fragment (sort of like an empty div but it doesn't change the DOM), so our final component will look like this:

// src/components/Layout.js
export default ({ children, noHeader }) => {
 const data = useStaticQuery(graphql`
    query {
      site {
        siteMetadata {
          title
          description
        }
      }
    }
  `)

  return (
    <>
      <Helmet>
      <title>{data.site.siteMetadata.title}</title>
      <meta name="description" content={data.site.siteMetadata.description} />
    </Helmet>
      <Container>
        {!noHeader && <Header />}
        <NavBar />
        {children}
        <Footer />
      </Container>
    </>
  )
}

When you run gatsby build and gatsby serve and then open the browser to localhost:9000, you should still see our site. Inspect the page and you should see both a title tag and a meta tag for the description.

Let's do an assignment in the next video to help you get more practice with this.