2

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.

3
  • 3
    this might help Commented Nov 18, 2019 at 14:44
  • I forgot to write that I have a restriction to install modules. Sorry Commented Nov 18, 2019 at 14:49
  • 2
    Possible duplicate of How do you set the document title in React? Commented Nov 18, 2019 at 14:58

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

Comments

0

It all depend on your use case, if you just wanna change the title of the page dynamically for a user, it's recommanded to use react-helmet.

Another solution is to use SSR, so you'll be able to set any metadata or title dynamically, but I assume you're not using SSR. In some case, like for content integration on another website, or when a robot is crawling for indexing, if you set dynamically with react-helmet or "document.title" it would not work so here is a pretty easy workaround

  1. Identify all user-agent of robots (Linkedin, Discord, X, ...)
  2. Create a /preview route on your backend which handle the url to serve back a html template with title and any metadata
  3. Add a redirection based on user agent from your frontend route to your backend route (/preview) directly within your web server (nginx in your conf, apache2 in the .htaccess)

In practice this will redirect all robot going to https://example.com to https://api.example.com/preview and this route need to serve something like

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My dynamic title</title>
    <meta name="description" content="A brief description of the page">
    <meta name="author" content="Your Name">
</head>
<body>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.