Adding Google Analytics to React

后端 未结 6 1538
别那么骄傲
别那么骄傲 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:43

    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

提交回复
热议问题