Table of Contents
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 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"23function App() {4 useEffect(() => {5 document.title = "My new title"6 }, [])78 return <div className="App"></div>9}1011export 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"23function App() {4 return (5 <div className="App">6 <Helmet>7 <title>Title using helmet</title>8 </Helmet>9 </div>10 )11}1213export 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!