How to listen to route changes in react router v4?

Kasper picture Kasper · Jan 28, 2017 · Viewed 146.1k times · Source

I have a couple of buttons that acts as routes. Everytime the route is changed, I want to make sure the button that is active changes.

Is there a way to listen to route changes in react router v4?

Answer

brickpop picture brickpop · Jun 7, 2017

I use withRouter to get the location prop. When the component is updated because of a new route, I check if the value changed:

@withRouter
class App extends React.Component {

  static propTypes = {
    location: React.PropTypes.object.isRequired
  }

  // ...

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      this.onRouteChanged();
    }
  }

  onRouteChanged() {
    console.log("ROUTE CHANGED");
  }

  // ...
  render(){
    return <Switch>
        <Route path="/" exact component={HomePage} />
        <Route path="/checkout" component={CheckoutPage} />
        <Route path="/success" component={SuccessPage} />
        // ...
        <Route component={NotFound} />
      </Switch>
  }
}

Hope it helps