Skip to content

Instantly share code, notes, and snippets.

@MattJonesCreation
Last active April 2, 2019 12:59
Show Gist options
  • Save MattJonesCreation/c53c4a21d3e9d0ba73eaf18531de459f to your computer and use it in GitHub Desktop.
Save MattJonesCreation/c53c4a21d3e9d0ba73eaf18531de459f to your computer and use it in GitHub Desktop.
Google Analytics Implementation for a Create React App Project
// utils/GoogleAnalytics.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactGA from 'react-ga';
import { Route } from 'react-router-dom';
class GoogleAnalytics extends Component {
componentDidMount () {
this.logPageChange(
this.props.location.pathname,
this.props.location.search
);
}
componentDidUpdate ({ location: prevLocation }) {
const { location: { pathname, search } } = this.props;
const isDifferentPathname = pathname !== prevLocation.pathname;
const isDifferentSearch = search !== prevLocation.search;
if (isDifferentPathname || isDifferentSearch) {
this.logPageChange(pathname, search);
}
}
logPageChange (pathname, search = '') {
const page = pathname + search;
const { location } = window;
ReactGA.set({
page,
location: `${location.origin}${page}`,
...this.props.options
});
ReactGA.pageview(page);
}
render () {
return null;
}
}
GoogleAnalytics.propTypes = {
location: PropTypes.shape({
pathname: PropTypes.string,
search: PropTypes.string
}).isRequired,
options: PropTypes.object
};
const RouteTracker = () => <Route component={GoogleAnalytics} />;
const init = (options = {}) => {
const isGAEnabled = process.env.NODE_ENV === 'production';
if (isGAEnabled) {
ReactGA.initialize("UA-000000000-1");
}
return isGAEnabled;
};
export default {
GoogleAnalytics,
RouteTracker,
init
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment