Change Page Title in React

Change the page title when the user routes to a new page.

A Great Tool

There are many ways to get the page title to change and some great tools to assist you. There is a particularly great tool that will do that and a bit more. It's called react-helmet.

It can set anything that occurs in the head of the document.

It has a great declarative API because it's exposed as just another component.

Using react-helmet

To use this feat of software engineering, we'll install it:

npm install react-helmet

And then use it inside of one or more of our components.

Let's say that we have a home page and an about page. We might have a top-level component as the entry point for each page. We would put a call to react-helmet in each of these components, assigning the respective titles:

import { Helmet } from 'react-helmet'

const Home = _ => 
  
Muffins R Us Welcome to muffin land. It's breakfast time!
const About = _ =>
About | Muffins R Us How we got into muffins.

No when your router changes components from Home to About or vice versa, the Helmet will engage and change your site's title.

Depending on your site design, you could change the site title even when the URL hasn't changed. Since the title is set when a component is rendered, all you'd need to do is render a component with a different </Helmet></code> declaration inside it, and the site title would change.</p><p>How else do you handle updating the page title in a React app?</p><p>Or have you found other interesting uses for <code>react-helmet</code>?</p></div></article></main></body><footer class="spacer"><nav class="main-footer__nav"><ul class="reset"><li>© 2024 Jake Trent</li><li><a class="hover pink" href="/post">[Posts]</a></li><li><a class="hover pink" href="/tags">[Tags]</a></li><li><a class="hover pink" href="mailto:hi@jaketrent.com">[Contact]</a></li><li><a class="hover orange" href="/post/feed.xml">[Feed]</a></li><li><a class="hover pink" href="/sitemap.xml">[Sitemap]</a></li><li><a class="hover pink" href="/life">[Life]</a></li></ul></nav></footer></html>