How to set up Google Analytics for React-Router?

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

    Note if you're using the react-router-dom package from react-router-4 you can handle this like so:

    import { Router, Route } from 'react-router-dom';
    import { createBrowserHistory } from 'history';
    
    const history = createBrowserHistory();
    const initGA = (history) => {
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
    
      ga('create', 'YOUR_IDENTIFIER_HERE', 'auto');
      ga('send', 'pageview');
    
      history.listen((location) => {
        console.log("tracking page view: " + location.pathname);
        ga('send', 'pageview', location.pathname);
      });
    };
    
    initGA(history);
    
    class App extends Component { //eslint-disable-line
      render() {
        return
          (
             
             
           )
      }
    }
    

    Note that this requires you to install the history package (npm install history). This is already a dependency of react-router-dom so you're not adding any page weight here.

    Also note: It is not possible to use the BrowserRouter component AND instrument your ga tracking this way. This is okay because the BrowserRouter component is just a really thin wrapper around the Router object. We recreate the BrowserRouter functionality here with where const history = createBrowserHistory();.

提交回复
热议问题