modifying head tags as side effects with nextjs

2020-05-14

 | 

~2 min read

 | 

354 words

When navigating around a digital store, it can be a nice enhancement to let the user know which page they’re on by updating the Head tag’s title.

(For more on the Head tag, see my previous post on the basics of the Head Tag)

NextJS makes this straightforward by allowing you to import the Head component from next/head and modify it from any page or component.

Let’s look at a small example.

Imagine a Meta component that’s imported on each Page in our NextJS app.

components/Meta.js
import Head from "next/head"

export const Meta = () => (
  <Head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta charSet="utf-8" />
    <link rel="shortcut icon" href="/static/favicon.png" />
    <title>My Store!</title>
  </Head>
)

Now, when we navigate to a single item’s detail page, we want to update the page title from My Store! to include the product’s title, e.g., My Store! | World's Best Pen (this works best when the user doesn’t have 89 tabs open).

components/ItemDetail.js
import Head from "next/head"
//...

export const ItemDetail = (props) => {
  return (
    <Query query={SINGLE_ITEM_QUERY} variables={{ id: props.id }}>
      {({ error, loading, data }) => {
        /*...*/
        const { id, title, description, largeImage } = data.item
        return (
          <ItemDetailStyles>
            <Head>              <title>My Site! | {title} </title>            </Head>            {/*...*/}
          </ItemDetailStyles>
        )
      }}
    </Query>
  )
}

Here, I’m using React-Apollo’s Query Higher Order Component to retrieve my item and render it to the page. Once it’s received, I am passing that title into the Head which will override the top level title tag.


Related Posts
  • Back To The Basics: HTML Head Tag


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!