Intercept/handle browser's back button in React-router?

high incompetance picture high incompetance · Sep 6, 2016 · Viewed 86.4k times · Source

I'm using Material-ui's Tabs, which are controlled and I'm using them for (React-router) Links like this:

    <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/>
    <Tab value={1} label="users" containerElement={<Link to="/dashboard/users"/>} />
  <Tab value={2} label="data" containerElement={<Link to="/dashboard/data"/>} />

If I'm currenlty visting dashboard/data and I click browser's back button I go (for example) to dashboard/users but the highlighted Tab still stays on dashboard/data (value=2)

I can change by setting state, but I don't know how to handle the event when the browser's back button is pressed?

I've found this:

window.onpopstate = this.onBackButtonEvent;

but this is called each time state is changed (not only on back button event)

Answer

Jay Shin picture Jay Shin · Jul 31, 2017

This is a bit old question and you've probably already got your answer, but for people like me who needed this, I'm leaving this answer.

Using react-router made the job simple as such:

import { browserHistory } from 'react-router';

componentDidMount() {
    super.componentDidMount();

    this.onScrollNearBottom(this.scrollToLoad);

    this.backListener = browserHistory.listen(location => {
      if (location.action === "POP") {
        // Do your stuff
      }
    });
  }

componentWillUnmount() {
    super.componentWillUnmount();
    // Unbind listener
    this.backListener();
}