This article describes two ways to change the document title in React Js.
- Using pure Javascript document.title
- Using NPM package React-Helmet
Using pure Javascript document.title
Here I use pure Javascript to set the page title.
import { useEffect } from "react"
export const SignupForm = () =>{
useEffect(() => {
document.title = "LearnBestCoding Page title"
})
return(
<>
<p>Some page content</p>
</>
)
}
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
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.