vijayst vijayst - 1 year ago 160
React JSX Question

Detect previous path in react router?

I am using react router. I want to detect the previous page (within the same app) from where I am coming from. I have the router in my context. But, I don't see any properties like "previous path" or history on the router object. How do I do it?

Answer Source

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 */}

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download