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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With