Ad

Update Document And App Bar Title When Using React Router

- 1 answer

I'm investigating the use of the react router in a TypeScript application. How would I update the document title (document.title) and the app bar title (<span className="appbartitle">Home</span>) in a SPA in response to the router navigation?

import React from 'react';
import {BrowserRouter as Router, Switch, Route, Link} from "react-router-dom";
import './App.css';

const App: React.FC = () => {
  return (
    <div className="App">
        <Router>
            <div className="appbar">
                <span className="appbartitle">Home</span>
                <span className="menuItem"><Link to="/">Home</Link></span>
                <span className="menuItem"><Link to="/about">About</Link></span>
                <span className="menuItem"><Link to="/dashboard">Dashboard</Link></span>
            </div>
            <Switch>
                <Route exact path="/"><Home /></Route>
                <Route path="/about"><About /></Route>
                <Route path="/dashboard"><Dashboard /></Route>
            </Switch>
        </Router>
    </div>
    );
}

export default App;

const Home = () => <div><h2>Home page</h2></div>;
const About = () => <div><h2>About page</h2></div>;
const Dashboard = () => <div><h2>Dashboard page</h2></div>;
Ad

Answer

Well, you can perform side effects inside your component. For example

import React, {useEffect} from 'react';
import {BrowserRouter as Router, Switch, Route, Link} from "react-router-dom";
import './App.css';
...
...
...
const Home = () => {
  useEffect(() => {
    // Update the document title using the browser API
    document.title = "[Your Title]";
    document.querySelector('.appbartitle').textContent = "[Your App Bar Title]"
  });

  return (<div><h2>Home page</h2></div>);
}
Ad
source: stackoverflow.com
Ad