Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get previous path? #1066

Closed
kjs3 opened this issue Apr 11, 2015 · 14 comments
Closed

How to get previous path? #1066

kjs3 opened this issue Apr 11, 2015 · 14 comments

Comments

@kjs3
Copy link

kjs3 commented Apr 11, 2015

When rendering a component I'd like to conditionally render a back button depending on what route they came from. If they copy/paste the url into another window, thereby having no history, don't render.

HTML5 History doesn't give any ability to inspect the previous path which seems the same as the goBack() method.

Is this history available in the context somewhere I'm not seeing?

@agundermann
Copy link
Contributor

You could store the previous path inside Router.run callback, but that would refer to the previously rendered path, not the previous path in browser history.

As far as I can tell, there's no way to get information about the previous item in browser history due to API limitations and browser discrepancies. I've tried to add some kind of tracking in the past that would enable this, but eventually gave up.

@kjs3
Copy link
Author

kjs3 commented Apr 11, 2015

@taurose By "previously rendered path" do you mean it would give me just the previous route segment in the cascade/route tree? I would definitely want to get the whole route after the tld.

It seems super useful for the router to be pushing/popping to a history array that is available in the router context. Maybe truncate it to some arbitrary number so it doesn't grow boundlessly as a user uses your site.

@agundermann
Copy link
Contributor

The last path that went through your run callback, which is usually the last path that you rendered with React.render(<Handler />). This can differ from browser history, e.g. after using browser back button it would refer to the next page in browser history.

var prevPath = null;
router.run(function(Handler, state) {
  React.render(<Handler prevPath={prevPath} />, document.body);
  prevPath = state.path;
});

@ryanflorence
Copy link
Member

we can't know that any better than your app. You'll just need to store something somewhere to indicate that this is the first render or not, like @taurose showed.

(though, we've thought about adding some "referrer" information to the new location objects in 1.0)

@mgreer
Copy link

mgreer commented Sep 10, 2015

How would one do this in 1.0.0beta4, since router.run is gone?

@ryanflorence
Copy link
Member

<Route component={App}>
  {/* ... other routes */
</Route>

var App = React.createClass({
  getInitialState () {
    return { showBackButton: false }
  },

  componentWillReceiveProps(nextProps) {
    var routeChanged = nextProps.location !== this.props.location
    this.setState({ showBackButton: routeChanged })
  }
})

@Chun-Yang
Copy link

Here is how to save the previous location to a global variable(or you can use a local variable). Let's say you want to get the previous location in window.previousLocation.

// NOTE: App should be in the top level!
<Route component={App}>
  {/* ... other routes */
</Route>

var App = React.createClass({
  componentWillReceiveProps() {
    window.previousLocation = this.props.location
  }
})

Now you can use window.previousLocation.pathname to get the pathname anywhere in your code, say in getInitialState in another react component.

@timqian
Copy link

timqian commented Nov 24, 2015

For react-router 1.x.x, you can go back and forth using history's goBack(), goForward() and go(n) method.@mgreer
https://github.com/rackt/history/blob/master/docs/GettingStarted.md
and this link might also be helpful:
https://github.com/rackt/react-router/blob/master/docs/guides/advanced/NavigatingOutsideOfComponents.md

@iest
Copy link
Contributor

iest commented Jun 7, 2016

Updated link from @timqian 's post for posterity: https://github.com/reactjs/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md

@hasibsahibzada
Copy link

hasibsahibzada commented Jan 18, 2017

Get the default function (goBack) from router that you get from ownProps in the mapStateToProps function call.
so you have goBack function as your component prop, then simply pass it to your onClick event of your button.
See sample example below:

import React, { Component, PropTypes } from 'react';

class Mycomponent extends Component {

  render() {
        const { label, goBack } = this.props;
        return (
            <button onClick={goBack}> {label}  </button>
        )
  }
}

Mycomponent.propTypes = {
    label: PropTypes.string.isRequired,
    goBack: PropTypes.func.isRequired
};

function mapStateToProps(state, ownProps) {
    return {
        goBack: ownProps.router.goBack
    };
}

export default connect(mapStateToProps)(Mycomponent);

@wfayeBerman
Copy link

I have a slightly similar question, but couldn't find anything explicit recommendations: how could one simple get information on what the last location was?

We already have browserHistory.getCurrentLocation(), is there a browserHistory.getLastLocation() or an equivalent? If the last location was not on the same site, this might be null but if it was, then this might be an object similar to what browserHistory.getCurrentLocation() returns.

Should I simply cache browserHistory.getCurrentLocation() as a variable lastLocation within my application?

@ChrisCinelli
Copy link

I agree that this would be useful.
I filed this remix-run/history#426

@hinok
Copy link
Contributor

hinok commented May 23, 2017

@wfayeBerman I implemented this functionality more as a proof of concept at the beginning but it seems that it's working very well for me so I decided to publish it as a npm package. Hope it will help someone.

It's still very young package, I will add tests in the near future. Generally it provides HOC withLastLocation and LastLocationProvider component. Usage should be straightforward.

https://github.com/hinok/react-router-last-location
https://www.npmjs.com/package/react-router-last-location

@remix-run remix-run deleted a comment from xiaoshuangLi Nov 8, 2017
@pladaria
Copy link

pladaria commented Aug 14, 2018

I needed previous path in a redux reducer. Solved writing a simple store middleware like this:

import {LOCATION_CHANGE} from 'react-router-redux';

let prevPathname = '';

export default () => next => action => {
    if (action.type === LOCATION_CHANGE) {
        const newAction = {
            ...action,
            payload: {
                ...action.payload,
                prevPathname,
            },
        };
        prevPathname = action.payload.pathname;
        return next(newAction);
    }
    return next(action);
};

Your reducer will receive pathname and prevPathname

@lock lock bot locked as resolved and limited conversation to collaborators Oct 13, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests