Skip to content

Instantly share code, notes, and snippets.

@magician11
Last active April 11, 2020 22: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 magician11/d4b306da003e2cf17a530d761d837a7b to your computer and use it in GitHub Desktop.
Save magician11/d4b306da003e2cf17a530d761d837a7b to your computer and use it in GitHub Desktop.
How to setup the React Google Analytics Module (react-ga) for your react.js app (with no routes).
import ReactGA from 'react-ga'; // https://github.com/react-ga/react-ga
import { React, Component } from 'react';
class MyApp extends Component {
constructor() {
super();
this.state = {
someData: null,
};
// Add your tracking ID created from https://analytics.google.com/analytics/web/#home/
ReactGA.initialize('UA-000000-01');
// This just needs to be called once since we have no routes in this case.
ReactGA.pageview(window.location.pathname);
}
render() {
return <h1>MyApp is being tracked by Google Analytics</h1>;
}
}
export default MyApp;
import React, { useEffect } from 'react';
import ReactGA from 'react-ga';
export default function App() {
useEffect(() => {
ReactGA.initialize('UA-000000-01');
ReactGA.pageview(window.location.pathname);
}, []);
return <h1>hello world</h1>;
};
@M-Fasciano
Copy link

Hi,
Thanks for the code snippet, but when I use it on my spa project I get this error "ReferenceError: window is not defined".
Any ideas why do I get this error?
Thanks
Michele

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment