DEV Community

Joma
Joma

Posted on

Dynamic tab title for your React app: two ways

  1. Using a custom hook
  2. Using React's built-in browser title component

Creating and calling a custom hook

If you want to create a custom hook to handle dynamic tab title, you can do it like this:

import {useEffect } from 'react'

function useTabTitle(title) {

  useEffect(() => {
    document.title = title;
  }, [title]);


}

export default useTabTitle
Enter fullscreen mode Exit fullscreen mode

useEffect hook will take a title prop as its param and fire whenever the title changes.

Whenever you want to set a different title for other pages, you'll just call this hook with the required param:

import useTabTitle from "../pageTtitles/changetabTitle"

const Dashboard = () => {
 useTabTitle(" My dashboard");

  return (
    <div>
      <p>This is the dashboard</p>
    </div>
  )
}

export default Dashboard
Enter fullscreen mode Exit fullscreen mode

Leveraging a built-in browser component

If you prefer much faster way and want to stick with the React's documentation (React documentation), you can just use a title tag as every other html tag in your React web application:

const Dashboard = () => {

  return (
    <div>
      <title>My dashboard</title>
      <p>This is the dashboard</p>
    </div>
  )
}

export default Dashboard
Enter fullscreen mode Exit fullscreen mode

Top comments (0)