react-router: how to get the previous route in onEnter handler?

T_Conroy picture T_Conroy · Apr 15, 2016 · Viewed 19.8k times · Source

I'm trying to find a way to read the previous route/path when a user hits a new one, within the onEnter handler.

I have a React Router structured like so:

    <Router history={history}>
      <div className="index">
        <Route
          path="/"
          component={ComposedAppComponent}
          onEnter={this.onEnterHandler.bind(this)}
        >
          <Route name="streamKey" path=":streamKey">
            <Route name="articleUri" path="(**)" />
          </Route>
        </Route>
      </div>
    </Router>

the function, onEnterHandler, looks like so:

  onEnterHandler(nextRouteState) {
    const { streamKey, splat } = nextRouteState.params;

    const nextPath = `/${streamKey}/${splat}`;
    const prevPath = // HOW DO I GET THE PREVIOUS PATH?
  }

I can't seem to find a way to read the previous route path the user was on... I need to make a comparison between the new route and previous one. Any input on how to approach this is much appreciated. :)

Cheers!

Answer

mirza.adipradhana picture mirza.adipradhana · Apr 16, 2016

Are you trying to get the previous path when the user navigate to new path through address bar or using react-router like this.context.router.push()?

If the navigation is using react-router, maybe these simple way would get what you're looking for:

1. Pass prevPath using query-params

Navigation might look like this:

`<Link to="/next" query={{ prevPath: this.props.location.pathname }}> Your Next path</Link>`

Now, you can get your prevPath value on onEnterHandler method by using this: nextState.location.query.prevPath

  • Cons: the query will appear on address bar.
  • Pros: you are still able to get your prevPath when user is navigating through address bar (direct path access).

2. Pass prevPath using state

Navigation might look like this:

`<Link to="/next" state={{ prevPath: this.props.location.pathname }}> Your Next path</Link>`

Now, you can get your prevPath value on onEnterHandler method by using this: nextState.location.state.prevPath

  • Cons: the query won't appear on address bar.
  • Pros: you are not able to get your prevPath when user is navigating through address bar (direct path access).

In addition, the cons of those method is you should assign a prevPath value into each of Link components. Create a wrapper component for the Link component would solve this issue.