Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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