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