4

I am wondering what would be the best pattern to subscribe for browser history changes with the latest version of react-router. I was reading the current documentation, but it looks like the only option which is mentioned there is by explicitly retrieving props passed by the <Match/> container to the render function or to the component. This solution is also described here:

https://stackoverflow.com/a/41006114/2817257

But what if I would like to get route parameters deeper in the component tree in a clean way?

What I am thinking about is to create a container component that retrieves router from context and subscribes to location changes. However, with the current version 4.0.0-alpha.6 even though the router object is already in the context, it only contains the following methods:

  • blockTransitions
  • createHref
  • replaceWith
  • transitionTo

which are not very promising, because it looks like router is not exposing the history object at all. Maybe there's some other object that's added to the context that could be helpful?

Community
  • 1
  • 1
Tomasz Lenarcik
  • 4,762
  • 17
  • 30

1 Answers1

0

react-router docs are down ATM, but in v3 you could pass an onUpdate function as a prop to the Router component to listen to router state changes.

Other option is to import browserHistory, which is is implemented with history (again v3 knowledge as v4 docs are down) and subscribe to history changes with listen, like this

import { browserHistory } from 'react-router'

browserHistory.listen((location, action) => {
  // do whatever you need here
})
jakee
  • 18,486
  • 3
  • 37
  • 42
  • 1
    Thanks for the answer. I think that unfortunately `browserHistory` instance is no longer available at `react-router` v4. – Tomasz Lenarcik Jan 30 '17 at 20:10
  • You can import createHistory from 'history/createBrowserHistory', assign the fn call to a variable, and set that to the history prop on the router. Then you'll have access to history wherever your history variable is exposed. – Ryan Feb 10 '17 at 06:23
  • Also note that the history.pushState() and history.replaceState() calls don't trigger the popstate event, so this answer alone won't cover all route changes. – Ryan Feb 10 '17 at 06:25