Search code examples
reactjsgoogle-analyticsreact-ga

Adding Google Analytics to React


I am trying to add Google Analytics to a React Web Application.

I know how to do it in HTML/CSS/JS sites and I have integrated it in an AngularJS app too. But, I'm not quite sure how to go about it when it comes to react.

With HTML/CSS/JS, I had just added it to every single page.

What I had done with AngularJS was adding GTM and GA script to index.html and added UA-labels to the HTML divs (and buttons) to get clicks.

How can I do that with React?

Please help!


Solution

  • Update: August 2023
    The old Package react-ga is now archived since it doesn't support Google Analytics version 4. There's a new package named react-ga4.
    Add it by running:
    npm i react-ga4

    Initialization

    import ReactGA from "react-ga4";
    
    ReactGA.initialize("your GA measurement id");
    

    To report page view:

    ReactGA.send({ hitType: "pageview", page: "/my-path", title: "Custom Title" });
    

    To report custom event:

    ReactGA.event({
      category: "your category",
      action: "your action",
      label: "your label", // optional
      value: 99, // optional, must be a number
      nonInteraction: true, // optional, true/false
      transport: "xhr", // optional, beacon/xhr/image
    });
    

    Update: Feb 2019
    As I saw that this question is being searched a lot, I decided to expand my explanation.
    To add Google Analytics to React, I recommend using React-GA.
    Add by running:
    npm install react-ga --save

    Initialization:
    In a root component, initialize by running:

    import ReactGA from 'react-ga';
    ReactGA.initialize('Your Unique ID');
    

    To report page view:

    ReactGA.pageview(window.location.pathname + window.location.search);
    

    To report custom event:

    ReactGA.event({
      category: 'User',
      action: 'Sent message'
    });
    

    More instructions can be found in the github repo


    The best practice for this IMO is using react-ga. Have a look at the github rep