How to set up Google Analytics for React-Router?

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

    Keep a reference to your history object. i.e.

    import { createBrowserHistory } from 'history';
    
    var history = createBrowserHistory();
    
    ReactDOM.render((
        
            [...]
    

    Then add a listener to record each pageview. (This assumes you've already set up the window.ga object in the usual manner.)

    history.listen((location) => {
        window.ga('set', 'page', location.pathname + location.search);
        window.ga('send', 'pageview');
    });
    

提交回复
热议问题