Detect previous path in react router?
Solution 1:
You can pass down state using the <Link>
component, in this case a pathname:
<Link to={{pathname: '/nextpath', state: { prevPath: location.pathname }}}>Example Link</Link>
You can then access prevPath
from this.props.location.state
in the next component
Solution 2:
You can save previous path in a componentWillReceiveProps
lifecycle method. The logic is very close to the example provided in troubleshooting section of react-router
docs.
<Route component={App}>
{/* ... other routes */}
</Route>
const App = React.createClass({
getInitialState() {
return { prevPath: '' }
},
componentWillReceiveProps(nextProps) {
if (nextProps.location !== this.props.location) {
this.setState({ prevPath: this.props.location })
}
}
})
And lately, access it from the state.
Solution 3:
If you're using react-router-redux
you can create a reducer which hooks into the events dispatched by react-router-redux.
export default function routerLocations(state = [], action) {
switch (action.type) {
case "@@router/LOCATION_CHANGE":
return [...state, action.payload]
default:
return state;
}
}