Home > database >  Changing page name based on current page / component
Changing page name based on current page / component

Time:10-13

i'd like to set my header to dynamically display the current page title. For example, when i jump to the component AvailableData, i'd like my Header component to display "Available data".

in App.js i set up a Router:

<Route exact path = "/" component= { AvailableData } />
...

and i use the Navbar component to move between pages

<div className="app-navigation">
    <ul>
        <li className="lnk-icon" >
            <NavLink to="/available-data" activeClassName="active">
            <img src="img/bookmark.svg" alt="Available data" />Available data</NavLink>
        </li>
    ...

inside header, the current page name should be displayed

    <div className="app-header">
         <div className="app-header__title">
             {title}  <-- Here
   </div>

CodePudding user response:

You can use the useLocation() hook and based on the current path, display the expected name.

For example, in your header component

import { useLocation } from "react-router-dom";


const Header = () => {
  const location = useLocation();

  const getCurrentTitle = () => {
    switch (location.pathname) {
      case "/":
      default:
        return "Home page";
      case "/available-data":
        return "Available data";
    }
  };

  return (
     <div className="app-header">
       <div className="app-header__title">
         {getCurrentTitle()}
       </div>
     </div>
  );
}
  • Related