Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router 4 history.listen never fires

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?

like image 792
ilyo Avatar asked May 21 '17 10:05

ilyo


People also ask

How do I clear the history on stack from react router?

index = -1; history. push(`/route`); This will clear the history and change for a new one. Save this answer.

How do I listen to route changes in react v5 router?

Use your router and pass your history object to it. In a component you want to listen to location changes on, import your history object and invoke the listen callback as you did previously. import history from '../myHistory'; ... useEffect(() => { const unlisten = history.

How do you prevent people from going back in react Dom router?

Using componentDidUpdate method of React page lifecycle, you can handled or disabled go back functionality in browser. basically componentDidUpdate method will call automatocally when component got updated. so once your component is updated you can prevent to go back as below.


2 Answers

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.

like image 142
Tharaka Wijebandara Avatar answered Sep 22 '22 10:09

Tharaka Wijebandara


The problem is that you are creating your own history object and passing it into the router. However, React Router v4 already provides this object for you, via this.props. (Importing Router has nothing to do with this)

componentDidMount() {
    this.props.history.listen((location, action) => console.log('History changed!', location, action));
}

You may need to layer your app a bit more though, like below, and put this componentDidMount method in your MyApp.jsx and not directly at the very top level.

<Provider store={store}>
    <BrowserRouter>
        <MyApp/>
    </BrowserRouter>
</Provider>

(Or use NativeRouter instead of BrowserRouter if you're doing React Native)

like image 27
Micros Avatar answered Sep 21 '22 10:09

Micros