How to set up Google Analytics for React-Router?

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

    Since react-router v5.1.0 this can be solved a lot easier with useLocation.

    usePageTracking.js

    import { useEffect} from "react";
    import { useLocation } from "react-router-dom";
    import ReactGA from "react-ga";
    
    const usePageTracking = () => {
      const location = useLocation();
    
      useEffect(() => {
        ReactGA.initialize("UA-000000000-0");
        ReactGA.pageview(location.pathname + location.search);
      }, [location]);
    };
    
    export default usePageTracking;
    

    App.js

    const App = () => {
      usePageTracking();
    
      return (...);
    };
    

    See also:

    • https://reactrouter.com/web/api/Hooks/uselocation
    • https://github.com/react-ga/react-ga/issues/122

    Here's a bit smarter version:

    usePageTracking.js

    import { useEffect, useState } from "react";
    import { useLocation } from "react-router-dom";
    import ReactGA from "react-ga";
    
    const usePageTracking = () => {
      const location = useLocation();
      const [initialized, setInitialized] = useState(false);
    
      useEffect(() => {
        if (!window.location.href.includes("localhost")) {
          ReactGA.initialize("UA-000000000-0");
        }
        setInitialized(true);
      }, []);
    
      useEffect(() => {
        if (initialized) {
          ReactGA.pageview(location.pathname + location.search);
        }
      }, [initialized, location]);
    };
    
    export default usePageTracking;
    

提交回复
热议问题