Skip to content

Instantly share code, notes, and snippets.

@bguiz
Last active July 24, 2017 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bguiz/da480dca9e36d3f13f6b379d5482af91 to your computer and use it in GitHub Desktop.
Save bguiz/da480dca9e36d3f13f6b379d5482af91 to your computer and use it in GitHub Desktop.
onUpdate in react-router-4
import { Component } from 'react';
import PropTypes from 'prop-types';
function RouteListenerFactory(plugins = []) {
plugins.forEach((plugin, pluginIdx) => {
if (!plugin.name) {
plugin.name = `routeListenerPlugin#${pluginIdx}`;
}
if (!plugin.initialise) {
plugin.initialise = (() => {
console.log(`initialise ${plugin.name}`);
});
}
if (typeof plugin.onRouteChange !== 'function') {
throw new Error(`Expected an onRouteChange function for ${plugin.name}`);
}
});
return class RouteListener extends Component {
static contextTypes = {
router: PropTypes.shape({
history: PropTypes.object.isRequired,
}).isRequired,
};
componentDidMount () {
plugins.forEach((plugin) => {
plugin.initialise();
plugin.onRouteChange(this.context.router.history.location);
});
this.context.router.history.listen(this.historyListener);
}
historyListener (location) {
plugins.forEach((plugin) => {
plugin.onRouteChange(location);
});
}
render () {
return this.props.children;
}
}
}
export default RouteListenerFactory;
// App.js
import RouteListener from './RouteListener.js';
import { RouteListenerPlugin as GoogleAnalyticsRouteListenerPlugin } from './GoogleAnalytics.js';
const RouteListenerComponent = RouteListener([
GoogleAnalyticsRouteListenerPlugin,
]);
const routes = []; //add some route definitions here
class App extends Component {
render() {
return (
<div className="App">
<Router>
<div>
<RouteListenerComponent>
<Switch>
{routes.map((route, idx) => {
return (<Route key={idx} {...route} />);
})}
<Route component={NotFoundPage} />
</Switch>
</RouteListenerComponent>
</div>
</Router>
</div>
);
}
}
// GoogleAnalytics.js
import GoogleAnalytics from 'react-ga';
import config from './config.js';
const RouteListenerGoogleAnalyticsPlugin = {
name: 'GoogleAnalytics',
initialise () {
GoogleAnalytics.initialize(
config.analytics.google.id,
config.analytics.google.options);
},
onRouteChange (location) {
GoogleAnalytics.set({
page: location.pathname,
});
GoogleAnalytics.pageview(location.pathname);
},
};
export {
RouteListenerGoogleAnalyticsPlugin as RouteListenerPlugin,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment