DEV Community

Cover image for How to set the document title in React?
collegewap
collegewap

Posted on • Originally published at codingdeft.com

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.



import { useEffect } from "react"

function App() {
  useEffect(() => {
    document.title = "My new title"
  }, [])

  return <div className="App"></div>
}

export default App


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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)