react-router-v4

How to listen to route changes in react router v4?


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?


Solution

  • 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>
      }
    }