'How to update the page title in the top Bar using useEffect , useState and LocalStorage?
I'm working on a reactJS project and i want to update the page title in the top Bar
knowing that each component separately : TopBarComponent, SideBarComponent, and otherPageComponents (pages contents).
I tried this :
in app.js
import './app.css';
import TopBar from "./components/TopBar/TopBar";
import SideBar from "./components/SideBar/SideBar";
import Home from "./pages/home/Home";
import Senior from "./pages/Seniors/Senior";
import Calendar from './pages/Calendar/Calendar';
import SeniorDetails from './pages/Seniors/SeniorDetails/SeniorDetails';
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
import { useEffect, useState } from 'react';
import Profile from './pages/Profile/Profile';
function App() {
const [title, setTitle] = useState('Home');
useEffect(()=>{
const data= localStorage.getItem('title');
if (data)
setTitle(JSON.parse(data));
},[]);
useEffect(() => {
localStorage.setItem('title', JSON.stringify(title));
});
return (
<Router>
<TopBar title={title} />
<div className="container" >
<SideBar setTitle={setTitle} />
<Switch>
<Route setTitle={setTitle} exact path="/" component={Home} />
<Route setTitle={setTitle} path="/senior" component={Senior} />
<Route setTitle={setTitle} path="/calendar" component={Calendar} />
<Route setTitle={setTitle} path="/profile" component={Profile} />
<Route setTitle={setTitle} path="/seniorDetails/1" component={SeniorDetails} />
</Switch>
</div>
</Router>
);
}
export default App;
and this is my TopBar.js where I consumed the title:
<nav aria-label="breadcrumb">
<ol className="breadcrumb bg-transparent mb-0 pb-0 pt-1 px-0 me-sm-6 me-5">
<li className="breadcrumb-item text-sm">
<a className="opacity-5 text-dark" href="/">
Pages
</a>
</li>
<li
className="breadcrumb-item text-sm text-dark active"
aria-current="page"
>
{title}
</li>
</ol>
<h6 className="font-weight-bolder mb-0">Dashboard</h6>
</nav>
the value of the title is saving correctly in LocalStorage but when I callback the previous component it returns the default value 'Home'.
Any solution, please ?!!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

