Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
  );};
like image 410
Subreena Avatar asked Aug 31 '25 05:08

Subreena


1 Answers

If you're looking for SEO, then create-react-app is not the solution here. Even if you share your page on social media, it won't show the metadata. You have to do server-side rendering for that. To read about server side rendering, do check here

https://medium.com/@yudhajitadhikary/client-side-rendering-vs-server-side-rendering-in-react-js-next-js-b74b909c7c51

like image 160
Prateek Thapa Avatar answered Sep 02 '25 19:09

Prateek Thapa