How to dynamically change the title of a website in react js (also in source code)?

Viewed 9084

I tried the react-helmet.I used React router and I want to change the title when route changes. With react-helmet I was able to change the title in the tab and console but sadly not in the source. I want to change the title in the source code also as it is very important for seo. In /public/index.html

<title>My Title</title>
<meta name="description" content="This is main page"/>

In src/app.js

import React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";
import {Helmet} from "react-helmet";
import Home from './Components/Pages/Home/';

function App() {
  return (
   <Router>
    <Helmet>
         <meta charset="utf-8" />
   <title>My title</title>
   <meta name="description" content="This is main page" />
        </Helmet>
      <Switch>
        <Route path="/home">
          <Home></Home>
        </Route>
        </Switch>
        </Router>
        );
        }
        export default App;
In Home.js

import React from 'react';
import {Helmet} from "react-helmet";

function Home() {
  return (
  <div>
           <Helmet>
         <meta charset="utf-8" />
   <title>Home Title</title>
   <meta name="description" content="This is home page" />
        </Helmet>

  </div>
  );};

5 Answers

Use React helmet to change your website title description. It also helps with SEO. https://www.npmjs.com/package/react-helmet

import React from "react";
import {Helmet} from "react-helmet";
 
class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <meta charSet="utf-8" />
                <title>My Title</title>
                <link rel="canonical" href="http://example.com" />
            </Helmet>
            ...
        </div>
    );
  }
};

You can change the title simply by doing document.title = '...'.

I put this in a useEffect for every top level component.

Google and Bing evaluate JS so will give no SEO disadvantage for setting the title in JS. However, other search engines might.

you should use context in react ( useContext hook ) and in every page you will going to set that title in variable named pageTitle of something which is declared in your app context finally you can use helmet package and place it in your title tag.

import React from "react";
 
class Application extends React.Component {
   state={
   title:"dynamic title"
  }
  componentDidMount(){
    document.title = this.state.title
  }
  render () {
    return (
        <div className="homePage"></div>
    );
  }
}
Related