React router 4 history.listen never fires

ilyo picture ilyo · May 21, 2017 · Viewed 7k times · Source

Switched to router v4 and history v4.5.1 and now history listener not working

import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory()

history.listen((location, action) => {
  console.log(action, location.pathname, location.state)  //  <=== Never happens
})

render(
  <Provider store={store}>
    <Router history={history}>
      ...
    </Router>
  </Provider>,
  document.getElementById('root')
)

Any ideas why it is being ignored?

Answer

Tharaka Wijebandara picture Tharaka Wijebandara · May 21, 2017

Since you are using BrowserRouter(with import alias Router as mentioned in comments of the question), it doesn't care the history prop you pass in. Instead of that it internally creates and assigns new browser history to the Router. So the history instance that you listen and being used in Router is not the same. That's why your listener doesn't work.

Import the original Router.

import { Router } from 'react-router-dom';

It will work as you expect.