javascriptreactjsdynamictitle

Dynamic page title with ReactJS


I want to make a Dynamic page title on ReactJS. I try a lot of things , but didn't succeed. I make an array with data:

let pageTitles = [
    {key:"/Home", title:"Welcome Home"},
    {key:"/SecondPage", title:"Shop"},
    {key:"/ThirdPage", title:"ContactUs"},
];

In html is only <title></title> , I use let pathname = window.location.pathname; If it return "/Home" or "/ThirdPage" to set a new title dynamically. I've tried something like that:

for (var i = 0, len = pageTitles.length; i < len; i++) {
        if (pageTitles[i].key === pathname) {
            var hhh = pageTitles[i].text;
        }
    }
document.title = hhh

But obviously didn't work. I'm sorry if there is a topic like that, but I didn't found it.I have a restriction to install modules.


Solution

  • If you need to avoid installing modules, you could do this as helper file, then just import it in module you need and call in componentDidMount

    export function seo(data = {}) {
      data.title = data.title || 'Default title';
      data.metaDescription = data.metaDescription || 'Default description';
    
      document.title = data.title;
      document.querySelector('meta[name="description"]').setAttribute('content', data.metaDescription);
    }
    
    import React from 'react';
    import {seo} from '../helpers/seo';
    
    export default class SomeClass extends Component {
      constructor(props) {
        super(props);
      };
    
      componentDidMount() {
        seo({
          title: 'This is my title only shown on this page',
          metaDescription: 'With some meta description'
        });
      }
    
      render() {
        return <h1>Hello World</h1>;
      }
    }
    

    You could also just call directly document.title = 'My new title' anywhere, but if you extract it as function you have the option to have default one and just provide override when you want to.

    Edit: upon inspecting your code, if you change hhh = pageTitles[i].text; to hhh = pageTitles[i].title; it will work. Would be nice to declare the var outside of the loop. Also would be nice to have default value.