Last active
April 11, 2020 22:02
-
-
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).
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 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; |
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, { 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>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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