Skip to content

How to set the document title in React?

Feb 22, 2023Abhishek EH2 Min Read
How to set the document title in React?

In this article, we will see different ways to add document title in React.

Using index.html

You can edit the index.html file inside the public directory to set the document title.

using index.html

Using the useEffect hook

The problem with updating the index.html directly is that we will not be able to have different titles for different pages. So we can make use of the useEffect hook as shown below to have a unique title per page.

1import { useEffect } from "react"
3function App() {
4 useEffect(() => {
5 document.title = "My new title"
6 }, [])
8 return <div className="App"></div>
11export default App

Using react-helmet library

While using useEffect will work fine, it involves many lines of code. It can get annoying to use it on many pages. To solve this we can use libraries like react-helmet.

Install react-helmet using the following command:

1npm i react-helmet

Now use it as shown below:

1import { Helmet } from "react-helmet"
3function App() {
4 return (
5 <div className="App">
6 <Helmet>
7 <title>Title using helmet</title>
8 </Helmet>
9 </div>
10 )
13export default App

Here the code looks more natural and you can add whichever tag you will use inside the head tag (meta, script, etc) using react-helmet.

If you have liked article, do follow me on twitter to get more real time updates!

Leave a Comment

© 2024 CodingDeft.Com