Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change page title on separate header component depending on route with React?

I am using React and have my project structured in a way that I have layout components and then the main page components. I want to change the title of the page in the header component depending on which route the user came to.

Here is my App.jsx:

import React, { Suspense, lazy, Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Header from './layout/Header.jsx';
import Footer from './layout/Footer.jsx';

const  Home = lazy(() => import('./pages/Home.jsx'));
const  Weather = lazy(() => import('.pages/Weather.jsx'));
const  Encryption = lazy(() => import('./pages/Encryption.jsx'));
const  Video = lazy(() => import('./pages/Video.jsx'));

class App extends Component {
render() {
    return (
        <Router>
            <>
                <Header/>
                <Suspense fallback={<div>Loading...</div>}>
                <Switch>
                    <Route exact path="/" component={Home}/>
                    <Route path="/weather" component={Weather}/>
                    <Route path="/encryption" component={Encryption}/>
                    <Route path="/video" component={Video}/>
                </Switch>
                </Suspense>
                <Footer/>

            </>
        </Router>
    );
}
}

export default App;

My Header.jsx component is like so:

import React, { Component } from 'react';

class Header extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
        <h1>Page Title</h1>
    );
  }
}

export default Header;
like image 341
yaserso Avatar asked Dec 17 '22 19:12

yaserso


1 Answers

import React, { Component } from "react";
import { withRouter } from "react-router-dom";
class Header extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    const path = this.props.location.pathname.slice(1);
    return (
      <div>
        <h1>{path}</h1>
      </div>
    );
  }
}

export default withRouter(Header);

Working example here: https://codesandbox.io/s/zl3y72k0pp

like image 59
h-des Avatar answered Jan 02 '23 16:01

h-des