React router v4 route onchange event

Is there a way to fire an event when route changes are made with router v4. I need to run the function on every route change. I am using BrowserRouter

and Switch

from react-router-dom

client side in react-redux generic app.

+3


source to share


2 answers


I solved this by wrapping my application with an additional component. This component is used in Route

, so it also has history

prop access .

<BrowserRouter>
  <Route component={App} />
</BrowserRouter>

      

The component App

subscribes to history changes, so I can do something on every route change:



export class App extends React.Component {
  componentWillMount() {
    const { history } = this.props;
    this.unsubscribeFromHistory = history.listen(this.handleLocationChange);
    this.handleLocationChange(history.location);
  }

  componentWillUnmount() {
    if (this.unsubscribeFromHistory) this.unsubscribeFromHistory();
  }

  handleLocationChange = (location) => {
    // Do something with the location
  }

  render() {
    // Render the rest of the application with its routes
  }
}

      

Not sure if this is the correct way to do it in V4, but I haven't found any other extensibility points on the router itself, so this seems to work. Hope it helps.

Edit: Perhaps you can also achieve the same goal by wrapping <Route />

in your own component and using something like componentWillUpdate

to detect location changes.

+4


source


React: v15.x, React Router: v4.x

components / core /App.js:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BrowserRouter } from 'react-router-dom';


class LocationListener extends Component {
  static contextTypes = {
    router: PropTypes.object
  };

  componentDidMount() {
    this.handleLocationChange(this.context.router.history.location);
    this.unlisten = 
this.context.router.history.listen(this.handleLocationChange);
  }

  componentWillUnmount() {
    this.unlisten();
  }

  handleLocationChange(location) {
    // your staff here
    console.log(`- - - location: '${location.pathname}'`);
  }

  render() {
    return this.props.children;
  }
}    

export class App extends Component {
  ...

  render() {
    return (
      <BrowserRouter>
        <LocationListener>
         ...
        </LocationListener>
      </BrowserRouter>
    );
  }
}

      



index.js:

import App from 'components/core/App';

render(<App />, document.querySelector('#root'));

      

0


source







All Articles