Home > Software engineering >  How to set a dynamic title based on routes for each pages?
How to set a dynamic title based on routes for each pages?

Time:01-06

Separate file should be created and dynamically we should change title how can we implement it

App.js

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
 </BrowserRouter>
  );
}

Routes.js

import { useRoutes } from "react-router-dom";
const Layout = React.lazy(() => import("/Layout.jsx"));
const Blogs = React.lazy(() => import("/Blogs.jsx"));
const NoPage = React.lazy(() => import("/NoPage.jsx"));
const Routes() {
 let element = useRoutes([
    {
      path: "/",
      element: <Suspense fallback={null}><Layout /></Suspense>

    
},
 {
      path: "/",
      element:  <Suspense fallback={null}><Blogs /></Suspense>
},

{
      path: "*",
      element: <Suspense fallback={null}><NoPage /></Suspense>
},
]);

  return element;
}

Based on routes how can we changes title of the each page dynamically by maintaining a single js file, and how can we have same logo for all the page along with the title

CodePudding user response:

For React 16.8 you can use the Effect Hook in function components:

import React, { useEffect } from 'react';

function Example() {
  useEffect(() => {
    document.title = 'My Page Title';
  }, []);
}

Without Hook:

import React from 'react'
import ReactDOM from 'react-dom'


class Example extends React.Component{
  componentDidMount(){
    document.title = "My Page Title"
  }

  render(){
    return(
      <b> your data</b>
    )
  }
}

You can also set it separately as a parent component.

import { useEffect } from "react";

const Page = (props) => {
  useEffect(() => {
    document.title = props.title || "";
  }, [props.title]);
  return props.children;
};

export default Page;  

Your Route:

 <Route
      path="/about"
      render={(props) => (
        <Page title="Index">
          <Index {...props} />
        </Page>
      )}
    />
    
    <Route
      path="/profile"
      render={(props) => (
        <Page title="Profile">
          <Profile {...props} />
        </Page>
      )}
    />

CodePudding user response:

You can use the name prop for your components.

import { useRoutes } from "react-router-dom";
const Layout = React.lazy(() => import("/Layout.jsx"));
const Blogs = React.lazy(() => import("/Blogs.jsx"));
const NoPage = React.lazy(() => import("/NoPage.jsx"));
const Routes() {
let element = useRoutes([
{
  path: "/",
  element: <Suspense fallback={null}><Layout title="Layout Page"/></Suspense>
},
{
   path: "/",
  element:  <Suspense fallback={null}><Blogs title="Blogs Page"/></Suspense>
},
{
  path: "*",
  element: <Suspense fallback={null}><NoPage title="404 Page"/></Suspense>
},
]);

   return element;
}
  • Related