How to set the document title in React Js

Last updated : Jul 30, 2023 12:00 AM

This article describes two ways to change the document title in React Js.

  1. Using pure Javascript document.title
  2. Using NPM package React-Helmet

Using pure Javascript document.title

Here I use pure Javascript to set the page title.

set the page titleDescription
import { useEffect } from "react"
export const SignupForm = () =>{
useEffect(() => {
  document.title = "LearnBestCoding Page title"
})
 return(
  <>
    <p>Some page content</p>
  </>
 )
}
Figure 1: React Js set page title
Figure 1: React Js set page title

But be aware that you cannot see these details if you view the page source because this is React Js.

Using NPM package React-Helmet

If you prefer not to use the above method for some reason, an NPM package is built just for this.

Install the NPM package by running:

npm i react-helmet

or, if you use Typescript, use:

npm i --save-dev @types/react-helmet
React HelmetDescription
import {Helmet} from "react-helmet";
export const SignupForm = () =>{
   return(
      < Helmet>
         <meta charSet="utf-8" />
         <title>LearnBestCoding Page title</title>
         <link rel="canonical" href="http://www.learnbestcoding.com" />
      </Helmet>
 )
}

Advantages of using react-helmet

React Helmet needs an additional NPM package. However, it has some advantages over the Javascript approach.

React Helmet allows me to nest header information. Meaning my child component's Helmet overrides my parent component's Helmet contents.

import { Helmet } from "react-helmet"
import { SignupForm } from "./components/Child"
export default const Parent = () => {
  return(
    <>
     <Helmet>
          <meta charSet="utf-8" />
          <title>Parent Page Title</title>
          <link rel="canonical" href="http://www.learnbestcoding.com" />
     </Helmet>
      <Child />
    </>
  )
}
import {Helmet} from "react-helmet";
export const Child = () =>{
 return(
    <Helmet>
          <meta charSet="utf-8" />
          <title>Child Page Title</title>
          <link rel="canonical" href="http://www.learnbestcoding.com" />
     </Helmet>
 )
}

In the above example, the Child component's Helmet content overrides the parent's Helmet details.

Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...