How to setup Google Analytics with React.js apps

[fusion_builder_container hundred_percent=”no” equal_height_columns=”no” menu_anchor=”” hide_on_mobile=”small-visibility,medium-visibility,large-visibility” class=”” id=”” background_color=”” background_image=”” background_position=”center center” background_repeat=”no-repeat” fade=”no” background_parallax=”none” parallax_speed=”0.3″ video_mp4=”” video_webm=”” video_ogv=”” video_url=”” video_aspect_ratio=”16:9″ video_loop=”yes” video_mute=”yes” overlay_color=”” video_preview_image=”” border_size=”” border_color=”” border_style=”solid” padding_top=”” padding_bottom=”” padding_left=”” padding_right=””][fusion_builder_row][fusion_builder_column type=”1_1″ layout=”1_1″ background_position=”left top” background_color=”” border_size=”” border_color=”” border_style=”solid” border_position=”all” spacing=”yes” background_image=”” background_repeat=”no-repeat” padding_top=”” padding_right=”” padding_bottom=”” padding_left=”” margin_top=”0px” margin_bottom=”0px” class=”” id=”” animation_type=”” animation_speed=”0.3″ animation_direction=”left” hide_on_mobile=”small-visibility,medium-visibility,large-visibility” center_content=”no” last=”no” min_height=”” hover_type=”none” link=””][fusion_text columns=”” column_min_width=”” column_spacing=”” rule_style=”default” rule_size=”” rule_color=”” hide_on_mobile=”small-visibility,medium-visibility,large-visibility” class=”” id=””]

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 A howto guide is available here.

Then in the parent component of your React.js app

  1. Install the react-ga module: yarn add 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 using either a class or the hooks approach.

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

Any questions, let me know!


7 responses to “How to setup Google Analytics with React.js apps”

  1. 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.

  2. 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

  3. Thanks for the article Andrew. Do you know how to track Page Load Time with ReactGA? I’m using ReactGA.timing, but I can’t seem to get the page load time to work.

  4. Can I place the GA verification code on a separate JS file e.g analytics.js and embed them on my pages? Will it work or I must need to add the exact code on all pages?

Leave a Reply

Your email address will not be published.