Detect previous path in react router?

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.


Instead of checking what the previous page is, approach the problem from a different angle. Pass the current page as props to the component or link that you're going to navigate to.

In the previous page or component that I'm calling history.push or clicking the link from, I add a state of the current page that I'm on e.g.

history.push(`/device/detail`, { from: 'device detail page' } );

I can then access what the previous page was using history.location.state.from


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