skip to Main Content

I am faced with a problem and I am hoping someone might know how to overcome it.

The pages across all of our site have a default title, as per our index.html file:

<html lang="en">
  <head>
    <title>My Page Title</title>
  </head>
  ...
</html>

This means that all tabs display the page title as per the index file.

On one page of the site, I want to override the title as per the information that is returned from a page load.

For example:

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

This works exactly as I would like, when the tab loads, the tab title is updated.

The issue however is when a user clicks a link to navigate away from that page. The tab title remains as the value that was loaded, despite another page having loaded within that tab. The tab title displays as that loaded value until the page is hard refreshed.

Is there any way for me to set the document title for a page via a load, like illustrated above, but to have it return to the default value once navigated away?

2

Answers


  1. useEffect can be given a return value, which should take the form of a function that will be called when the component (or specifically the hook) unmounts.

    You can use this:

    useEffect(() => {
      const displayTitle = loadTitle();
      document.title = displayTitle;
    
      return () => document.title = ""; // However you'd like to reset the title
    }, []);
    

    See useEffect docs.

    Login or Signup to reply.
  2. So it depends on the structure of your page, if your are using the same components for several page, say for instance a dynamic product details page of this format /product/${product_id} then you need to update your use effect so that everytime the product_id changes the document.title should be set on not only on initial render.

    useEffect(() => {
     if(product_id){
        const displayTitle = loadTitle();
        document.title = displayTitle;
     }
    }, [product_id]);
    

    Alternatively, you can use the react-helmet package to display document title for each page. The documentation https://www.npmjs.com/package/react-helmet provides all you need.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search