Last active
February 21, 2019 02:39
-
-
Save mikehibm/c6271f1f3fe7bda7771dc0342cc525f6 to your computer and use it in GitHub Desktop.
A react component to use Google Analytics with React Static.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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