When working with React Router v4, we may want to detect route changes for analytics, logging, or other side effects. However, BrowserRouter does not expose the history object directly. To listen for route changes in this way, we need to use the Router component instead of BrowserRouter and provide it with the history object you created.
Here’s the corrected code:
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, Link } from 'react-router-dom'; import { createBrowserHistory } from 'history'; const history = createBrowserHistory(); history.listen((location, action) => { console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`); console.log(`The last navigation action was ${action}`); }); const A = () => <div>A <Link to="/b">b</Link></div>; const B = () => <div>B <Link to="/a">a</Link></div>; ReactDOM.render( <Router history={history}> <div> <div>Hello!</div> <Route path="/a" component={A} /> <Route path="/b" component={B} /> </div> </Router>, document.getElementById('root') );
By replacing BrowserRouter with Router and passing the custom history object as a prop, we ensure that the history.listen callback correctly detects and logs route changes.
Work with our skilled React developers to accelerate your project and boost its performance.
Hire Reactjs Developers