reactjs 将 Google Analytics 添加到 React

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49279820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:29:04  来源:igfitidea点击:

Adding Google Analytics to React

reactjsgoogle-analyticsreact-ga

提问by Raj

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

我正在尝试将 Google Analytics 添加到 React Web 应用程序。

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.

我知道如何在 HTML/CSS/JS 站点中执行此操作,并且我也将它集成到了 AngularJS 应用程序中。但是,当涉及到反应时,我不太确定如何去做。

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

使用 HTML/CSS/JS,我刚刚将它添加到每个页面。

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.

我对 AngularJS 所做的是将 GTM 和 GA 脚本添加到 index.html 并将 UA 标签添加到 HTML div(和按钮)以获得点击。

How can I do that with React?

我怎么能用 React 做到这一点?

Please help!

请帮忙!

回答by Matan Bobi

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

更新:2019 年 2 月
当我看到这个问题被大量搜索时,我决定扩展我的解释。
要将 Google Analytics 添加到 React,我建议使用 React-GA。
通过运行添加:
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

更多说明可以在github repo中找到



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

此 IMO 的最佳实践是使用 react-ga。看看github 代表

回答by cameck

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

在不使用包的情况下,我会这样做:

In your index.js(in the rendermethod):

在您的index.js(在render方法中):

    {/* 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');
};

回答by Giwan

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

如果您不想使用包,这就是它在 React 应用程序中的工作方式。在 index.html 中添加“gtag”

<!-- 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"
        });

回答by utkarsh

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

您可以检查的另一个很棒的库是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.

它很容易与 react/redux 应用程序集成,并且有一个很好的文档。ReactGA 也很好,但是有了 redux-beacon,你不会用谷歌分析代码混淆你的应用程序代码,因为它通过自己的中间件工作。

回答by William

I suggest embedding the Segment scriptinto your index.html, use the analytics library that is accessible on the windowobject, and add tracking calls onto React's event handlers:

我建议将Segment 脚本嵌入到您的 中index.html,使用window对象上可访问的分析库,并将跟踪调用添加到 React 的事件处理程序:

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.

我是https://github.com/segmentio/analytics-react的维护者。如果您想通过使用一个单一的 API 来管理您的客户数据来解决这个问题,并且能够集成到任何其他分析工具(我们支持 250 多个目的地)而无需编写任何额外代码,我建议您检查一下。