How to setup Google Analytics with React.js apps

If you have a single page app that has no routes, getting visitors tracked with Google Analytics is pretty straight forward using the React Google Analytics Module.

First create your tracking ID from Google Analytics by going to https://analytics.google.com/ A howto guide is available here.

Then in the parent component of your React.js app

  1. Install the react-ga module: npm install --save react-ga
  2. Import this module at the top of the app: import ReactGA from 'react-ga';
  3. And add the 2 lines of code into your constructor as shown below on lines 12 and 14.

I had data being tracked within 24 hours from adding this module.

If you are using react-router, there is a little more config as outlined here.

Any questions, let me know!

 

By | 2016-11-30T07:24:25+00:00 November 30th, 2016|gist|4 Comments

About the Author:

Andrew Golightly is the lead web developer here at Golightly+. He is a passionate fullstack JavaScript developer. And creates native apps too using React Native. To balance his love for coding, he also works as a counsellor.

4 Comments

  1. David October 27, 2017 at 3:53 pm - Reply

    Hey Man thank you! I was looking for this for awhile :)

    Now do I need to do that for each component? I have only done it on the main component that is first loaded.

    • Andrew January 4, 2018 at 2:35 am - Reply

      Hey David. You only need it on the main component for single page apps. And you’re welcome!

  2. Johnny Koo February 26, 2018 at 4:36 pm - Reply

    Hello Andrew, Thanks a lot for your post.
    BTW, I’m running my CRA in my localhost computer. Should I deploy CRA up online for GA to track my landing page? or is it possible while i’m working in my localhost dev environment?
    Thank you

Leave A Comment