How to set up Google Analytics for React-Router?

后端 未结 15 662
名媛妹妹
名媛妹妹 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:18

    Based on @david-l-walsh and @bozdoz suggestions

    I created a HOC that execute the window.ga('set','page','{currentUrl}) and window.ga('send', 'pageview'); function and is easly used directly in the router page...

    this is the HOC:

    import React from 'react';
    import { history } from '../../store'; // or wherever you createBrowserHistory(); invokation is
    
    function withGAHistoryTrack(WrappedComponent) {
      return class extends React.Component {
        constructor(props) {
          super(props);
        }
    
        componentDidMount() {
          const { location } = history;
          const page = location.pathname + location.search;
    
          if (typeof window.ga === 'function') {
            window.ga('set', 'page', page);
            window.ga('send', 'pageview');
          }
        }
    
        render() {
          return ;
        }
      };
    }
    
    export default withGAHistoryTrack;
    

    and is used this way in the router page:

    
    

提交回复
热议问题