Skip to content

Instantly share code, notes, and snippets.

@mikehibm
Last active February 21, 2019 02:39
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 mikehibm/c6271f1f3fe7bda7771dc0342cc525f6 to your computer and use it in GitHub Desktop.
Save mikehibm/c6271f1f3fe7bda7771dc0342cc525f6 to your computer and use it in GitHub Desktop.
A react component to use Google Analytics with React Static.
import React, { Component } from 'react';
import { Head, withSiteData } from 'react-static';
// Reference URL
// https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
// https://github.com/googleanalytics/autotrack#urlchangetracker
class GoogleAnalytics extends Component {
componentDidMount() {
// Ignore if not running on browser.
if (typeof document === 'undefined') return;
// gaID is injected by withSiteData. It's supposed to be defined in the static.config.js file.
const { gaID } = this.props;
// Load analytics.js
(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');
// Initialize Google Analytics.
ga('create', gaID, 'auto');
ga('send', 'pageview');
// Enable auto-tracking for each time the URL changes after the first loading.
ga('require', 'urlChangeTracker');
}
render() {
return (
<Head>
<script async src="autotrack.custom.js" />
</Head>
);
}
}
export default withSiteData(GoogleAnalytics);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment