Skip to content

Instantly share code, notes, and snippets.

@tomfa
Last active September 25, 2016 13:02
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 tomfa/fc334a7e69f6289d81168b31ebe76735 to your computer and use it in GitHub Desktop.
Save tomfa/fc334a7e69f6289d81168b31ebe76735 to your computer and use it in GitHub Desktop.
Using Google Analytics in React Redux
/*
Getting Google Analytics ID from environment variable GA_ID
This should be set on the form UA-8401XXXX-X and can be set by:
1) in package.json under "scripts": {
"start": "GA_ID=UA-8401XXXX-X node server.js"
}
2) In webpack, under plugins:
new webpack.EnvironmentPlugin([ 'API_URL', 'GA_ID' ])
* Remember to call analyticsInit() once when application is initialized (e.g. in your index.js)
*/
export function analyticsInit() {
if (window.ga !== undefined) {
return;
}
let gaId = process.env.GA_ID;
if (!gaId) {
throw 'Exception: GA_ID not found as an environment variable';
}
/* eslint-disable */
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
/* eslint-enable */
window.ga('create', gaId, 'auto');
window.ga('set', 'anonymizeIp', true);
}
export function registerPageView(title) {
window.ga('send', {
hitType: 'pageview',
title: title
});
}
export function sendCustomEvent(category, action, label, value=1) {
window.ga('send', {
hitType: 'event',
eventCategory: category,
eventAction: action,
eventLabel: label,
eventValue: value
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment