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.
import { useEffect } from "react"
function App() {
useEffect(() => {
document.title = "My new title"
}, [])
return <div className="App"></div>
}
export 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:
npm i react-helmet
Now use it as shown below:
import { Helmet } from "react-helmet"
function App() {
return (
<div className="App">
<Helmet>
<title>Title using helmet</title>
</Helmet>
</div>
)
}
export 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.
Top comments (0)