2
votes

In older versions of React Router, the state had a redirectPath state object that you were able to get the previous URL from. In the new version this is no longer the case. When navigating to a new URL via history.push, all that shows up is the new URL, with no apparent way to get the URL that you navigated from previously. Is there some functionality either in React Router or the history package itself that allows you to get the previous URL?

We are using goBack and that seems to work but if the user is going to a page out of the app (e.g. google) and go back to the app the goBack function will route to google again. How can we fix this?

Thank you

1

1 Answers

7
votes

You could push extra information in state: {} like

<Link to={{ pathname: '/about', state: { fromHome: true } }}>About</Link>

Then when route has changed, you could access state object and check how user has navigated to your route.

Today I created the package react-router-last-location which provides:

  • withLastLocation(), higher order component which pass lastLocation as a prop to your component
  • <LastLocationProvider /> component which should used inside <Router />.

Example usage

An entry point of your app

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import { LastLocationProvider } from 'react-router-last-location';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
import Logger from './components/Logger';

const App = () => (
  <Router>
    <LastLocationProvider>
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/contact">Contact</Link></li>
        </ul>

        <hr />

        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />

        <hr />

        <Logger />
      </div>
    </LastLocationProvider>
  </Router>
);

render(<App />, document.getElementById('root'));

A component which should have access to the last location

import React from 'react';
import { withLastLocation } from 'react-router-last-location';

const Logger = ({ lastLocation }) => (
  <div>
    <h2>Logger!</h2>
    <pre>
      {JSON.stringify(lastLocation)}
    </pre>
  </div>
);

export default withLastLocation(Logger);

You can install it from npm

npm install react-router-last-location --save