I have to implement some business logic depending on browsing history.
What I want to do is something like this:
reactRouter.onUrlChange(url => {
this.history.push(url);
});
Is there any way to receive a callback from react-router when the URL gets updated?
If you want to listen to the
history
object globally, you'll have to create it yourself and pass it to theRouter
. Then you can listen to it with itslisten()
method:Even better if you create the history object as a module, so you can easily import it anywhere you may need it (e.g.
import history from './history';
You can make use of
history.listen()
function when trying to detect the route change. Considering you are usingreact-router v4
, wrap your component withwithRouter
HOC to get access to thehistory
prop.history.listen()
returns anunlisten
function. You'd use this tounregister
from listening.You can configure your routes like
index.js
and then in AppContainer.js
From the history docs:
When you are using react-router v3 you can make use of
history.listen()
fromhistory
package as mentioned above or you can also make usebrowserHistory.listen()
You can configure and use your routes like