
React: Dynamic Headers For SEO
Here’s the situation. You’re making a website. On that website are a bunch of pages with different content. Let’s call it a blog.
You want to make sure that each post that you have has it’s own header tags so that when Google or Bing come to look they can find information that’s important to users:

1. Title
2. Description
There are plenty of other tags you can mess around with if you want. Which ones are important is up for you to decide¹. For this example those are the two we’ll be working with.
Those two tags correspond to what a searcher will see on Google.

The problem with single page web apps (SPA’s) is that you are injecting code into your base index.html file. You aren’t creating a new html file every time you load page. So your headers are static to what you have in your base index file.
To solve this problem we’re going to use a nifty little tool called Helmet. Helmet lets us write our header code one time and then place it into any other component we want. When we do this it takes the tags we give it and places them in the correct header spot every time we load a page that we’ve placed the Helmet in.
import { Helmet } from "react-helmet"class HelmetComponent extends React.Component { render() { return ( <Helmet> Everything that we write in here will be placed in the head section of our index.html file. Think of it just like a helmet. A helmet goes on top. That's exactly what this does. </Helmet> ) }
}export default HelmetComponent
Inside our Helmet component we place the tags we want to set.
<Helmet> <title>This is a great title</title>
<meta name='description' content="This content is uh-mazing!" /></Helmet>
However, we want these tags to be set dynamically, according to the content for each individual blog post that we have. Let’s assign the tags dynamically via props.
<Helmet> <title>{this.props.title}</title>
<meta name='description' content={this.props.description} /></Helmet>
And then in our post file we can simply pass the props that we need.
<HelmetComponent title='This is a great title' description='This content is uh-mazing!' />That’s all there is to it. I can’t think of how it could be much easier than that. It’s the best way I’ve found to set header tags dynamically on SPA’s.
*I’m personally using this setup on client-side rendered apps. Helmet performs exactly the same if you are working with server-side rendered apps. With one important difference…
¹From my experience Twitter Cards and Open Graph tags will not lead to the outcomes you want. I have yet to be able to validate a Twitter Card setup using any method on a client-side SPA, not just this Helmet method.
Help spread React by tappin’ on that little heart. Cheers!
phil&drews blog
Originally published at philandrews.io.
