5

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!

tdc
  • 5,174
  • 12
  • 53
  • 102

1 Answers1

12

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.

Community
  • 1
  • 1
  • How would a wrapper around the `Link` component look like? I'm a beginner to React, so I apologize if that is somewhat of a novice question. @mirza.adipradhana – Jay S. Sep 08 '16 at 02:40
  • @JayS. you would create a HOC (higher order component) - lets call it ``. Inside it you'd have a normal `` however you'd pass it the `query`/`state` prop. Then anytime you use `` instead of `` you don't need to specify the `query`/`state`, since the wrapper you created will pass it in for you automatically. – miketery Jun 02 '18 at 17:35