How to set up Google Analytics for React-Router?

后端 未结 15 648
名媛妹妹
名媛妹妹 2020-12-12 12:25

I\'m trying set up Google Analytics on my react site, and have come across a few packages, but none of which has the kind of set up that I have in terms of examples. Was ho

15条回答
  •  轮回少年
    2020-12-12 13:03

    Given that google analytics is loaded and initialised with a tracking id.

    Here is a solution for react-router version 4 using the component to track page views.

     {
      if (typeof window.ga === 'function') {
        window.ga('set', 'page', location.pathname + location.search);
        window.ga('send', 'pageview');
      }
      return null;
    }} />
    

    You simply render this component inside the (but not as a direct child of a ).

    What happens is that whenever the location prop changes it causes a re-render of this component (not actually rendering anything) that fire a pageview.

提交回复
热议问题