Adding Google Analytics to React

2020-05-17 01:34发布

问题:

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!

回答1:

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



回答2:

Without using a package this is how I would do it:

In your index.js (in the render method):

    {/* Global site tag (gtag.js) - Google Analytics */}
    <script
      async
      src="https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID"
    />
    <script>{injectGA()}</script>

And outside the class:

const injectGA = () => {
  if (typeof window == 'undefined') {
    return;
  }
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    window.dataLayer.push(arguments);
  }
  gtag('js', new Date());

  gtag('config', 'YOUR_TRACKING_ID');
};


回答3:

If you prefer not to use a package this is how it can work in a react application. Add the "gtag" in index.html

<!-- index.html -->

<script>
            window.dataLayer = window.dataLayer || [];
            function gtag() {
                dataLayer.push(arguments);
            }
            gtag("js", new Date());

            gtag("config", "<GA-PROPERTYID>");
        </script>

In the submit action of the login form, fire off the event

window.gtag("event", "login", {
            event_category: "access",
            event_label: "login"
        });


回答4:

One other great library that you can check is redux-beacon.

It gets integrated very easily with react/redux application and has a great documentation for it. ReactGA is good too but with redux-beacon, you won't clutter your app code with google analytics code as it works via its own middleware.



回答5:

I suggest embedding the Segment script into your index.html, use the analytics library that is accessible on the window object, and add tracking calls onto React’s event handlers:

export default class SignupButton extends Component {
  trackEvent() {
    window.analytics.track('User Signup');
  }

  render() {
    return (
      <button onClick={this.trackEvent}>
        Signup with Segment today!
      </button>
    );
  }
}

I’m the maintainer of https://github.com/segmentio/analytics-react. I recommend checking it out if you want to solve this problem by using one singular API to manage your customer data, and be able to integrate into any other analytics tool (we support over 250+ destinations) without writing any additional code.