Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save liesislukas/da29cc8e0e7f44d43251e77f1d0415e8 to your computer and use it in GitHub Desktop.
Save liesislukas/da29cc8e0e7f44d43251e77f1d0415e8 to your computer and use it in GitHub Desktop.
/*
To enable google analytics with autotracker do these steps:
1. Add analytics script to head, i used <Helmet /> so one more entry to scripts array:
{async: true, src: 'https://www.google-analytics.com/analytics.js'},
2. add code below to routes.js
P.s. to generate static files this line is added, because document obj. is missing at that moment.
if (typeof document !== 'undefined') {
}
*/
if (typeof document !== 'undefined') {
require('autotrack'); // Google analytics
ga('create', 'UA-00000000-1', 'auto');
ga('require', 'cleanUrlTracker', {
trailingSlash: 'add',
});
ga('require', 'outboundLinkTracker');
ga('require', 'urlChangeTracker', {
shouldTrackUrlChange: (newPath, oldPath) => {
return newPath && oldPath;
}
});
ga('require', 'pageVisibilityTracker'); // session timeouts if it's left in some tab
ga('require', 'socialWidgetTracker');
ga('require', 'eventTracker', {
events: ['click'],
attributePrefix: 'data-ga-',
});
}
const _route_change_handler = () => {
if (typeof ga !== 'undefined') {
ga('send', 'pageview');
}
};
export default (
<Route
...
onChange={(prevState, nextState, replace) => {
_route_change_handler();
return true;
}}
onEnter={(nextState) => {
_route_change_handler();
return true;
}}
...
>
...
</Route>
);
@DavidWells
Copy link

Looks awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment