Skip to content
react

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"
2
3function App() {
4 useEffect(() => {
5 document.title = "My new title"
6 }, [])
7
8 return <div className="App"></div>
9}
10
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"
2
3function App() {
4 return (
5 <div className="App">
6 <Helmet>
7 <title>Title using helmet</title>
8 </Helmet>
9 </div>
10 )
11}
12
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.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com