将 Google Analytics 添加到 React

IT技术 reactjs google-analytics react-ga
2021-05-07 07:35:54

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

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

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

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

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

请帮忙!

4个回答

更新:2019 年 2 月
当我看到这个问题被大量搜索时,我决定扩展我的解释。
要将 Google Analytics 添加到 React,我建议使用 React-GA。
通过运行添加:
npm install react-ga --save

初始化:
在根组件中,通过运行进行初始化:

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

报告页面浏览量:

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

报告自定义事件:

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

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


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

不使用包,这就是我的做法:

在您的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>

课外:

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

如果您不想使用包,这就是它在 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>

在登录表单的提交动作中,触发事件

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

您可以检查的另一个很棒的库是redux-beacon

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