ReactRouter "on change" event?

I want to install the analytics handler on my single-page application and would like to commit every route change in the main route. I acknowledge that ReactRouter offers an onEnter route onEnter ; however, this will require a separate installation of the handler on each route. I could create a subclass of Route that automatically populated onEnter , but then I could not override onEnter and still hold the analytics tracking handler.

What would be the best way to listen for any changes within a given root route?

+8
reactjs react-router
source share
4 answers

You can use static-router willTransitionTo static function to detect route changes and emit transition.path in a ga() function call, for example:

 var App = React.createClass({ mixins: [Router.State], statics: { willTransitionTo: function(transition, params, query, props) { ga('send', 'pageview', {'page': transition.path}); } }, render: function() { return ( <div> <RouteHandler /> </div> ); } }); 

A more complete example can be seen in this answer .

+8
source share

The answer was (figuratively) looking in my face.

When the router starts, you call Router.run(routes, callback) . A callback is called each time the route is changed. Therefore, the following code works the way I wanted:

 Router.run(routes, function (Handler) { doSomethingAnalytics(document.location.hash); React.render(<Handler/>, document.body.querySelector('#content')); }); 
+3
source share

this function is called every time the route changes

 const history = syncHistoryWithStore(browserHistory, store); history.listen((location)=>{ console.log(location) }); 
0
source share

Reaction: 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 share

All Articles