Adding Google Analytics to React

后端 未结 6 1548
别那么骄傲
别那么骄傲 2021-01-30 16:23

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

6条回答
  •  悲&欢浪女
    2021-01-30 16:49

    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 */}
        
    

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

提交回复
热议问题