cks
cks

Reputation: 570

Detect React Router Transition in ES6 Class

I'm trying to detect a route change caused by clicking on a <Link>, so that I can change the state of my component when the route changes. I've seen a lot of places suggest that you can use router.addTransitionHook, but I have a couple problems with this.

  1. I can't find any real documentation for addTransitionHook, and it sounds like it might have been replaced.
  2. I can't figure out how to get access to the router. Supposedly it's available under context.router in the constructor. I've tried everything suggested here (i.e. Component.contextTypes = { router: React.PropTypes.func.isRequired }) and I'm not getting anything except undefined for my context.router. Do I need to do something when I create the router in order for the components to have access to context?

There are a couple proposed solutions that involve mixins. The Lifecycle Mixin provides access to routerWillLeave. That seems like what I want, but mixins aren't available in ES6 classes.

Maybe I should try defining onEnter when I create the router as described here, but I'd rather not have to add any code to the router declaration. That doesn't seem like a good solution.

tldr; What's the best way to detect a React route change in an ES6 class?

Upvotes: 2

Views: 738

Answers (3)

Rajiv
Rajiv

Reputation: 457

history.listenBefore is not supported in React Router V4. Instead use history.block for blocking transition. And history.listen((location, action) => { // do something }) for listening to route transition . Check the docs here history

Upvotes: 1

cks
cks

Reputation: 570

I never figured out how to use events to solve my problem, but I realized what I should be doing is using lifecycle methods instead. My route was <Route name="routename" component={RouteApp} path="/routename/:urlKey" />. What I really cared about was when the urlKey param changed, and when that happens, the props of your component will change. Thus, I was able to put the code inside the componentWillReceiveProps lifecycle method.

Upvotes: 0

knowbody
knowbody

Reputation: 8276

If I understood you correctly you want to use listenBefore function from History module.

So you could use it like:

history.listenBefore((location) => {
  // ...
});

or if you need to transition asynchronously, then:

history.listenBefore((location, callback) => {
  // ...
});

Check for more in the Confirming Navigation docs.

Upvotes: 0

Related Questions