How to set up Google Analytics for React-Router?

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

    here is a simplest way to track all paths with some work arounds:

    npm i --save history react-ga

    create a file history.js

    import { createBrowserHistory } from "history"
    import ReactGA from "react-ga"
    
    ReactGA.initialize(process.env.REACT_APP_GA)
    
    const history = createBrowserHistory()
    history.listen((location) => {
        ReactGA.pageview(location.pathname)
    })
    
    // workaround for initial visit
    if (window.performance && (performance.navigation.type === performance.navigation.TYPE_NAVIGATE)) {
        ReactGA.pageview("/")
    }
    
    export default history
    

    and then import it to where is set your Router

    import history from "./history"
    
    ...
    
    class Route extends Component {
    render() {
        return (
            
                
                  
                  ...
                
            
        )
    }
    
    export default Route
    

    References:

    Gustavo Gonzalez | medium.com

    History | GitHub

提交回复
热议问题