How to use Google Analytics with React?

六眼飞鱼酱① 提交于 2019-12-05 05:42:46

问题


In my react app I have some pages:

  1. Main
  2. Service
  3. Contact
  4. Profile (private)
  5. etc..

I need to track users activity with Google Analytics. I googled react-ga and it's just fine. But with this library I have to initialize my GA on every route I use. For example:

Route "/" - main page:

class Main extends Component {

    componentDidMount() {
        initGA();
    }

    render() {
        return (
            <div>
                <Component1 />
                <Component2 />
            </div>
        )
    }
}

My initGA() looks like:

import ReactGA from 'react-ga';

export const initGA = () => {
    ReactGA.initialize('UA-00000000-1');
    ReactGA.pageview(window.location.pathname + window.location.search);
    console.log(window.location.pathname + window.location.search);
}

My App class looks like:

class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <div className="App">

                    <Switch>
                        <Route exact path="/" component={Main} />
                        <Route exact path="/signup" component={SignupLayout} />
                        <Route component={PublicLayout} />
                    </Switch>

                </div>
            </BrowserRouter>
        );
    }
}

In my way of using react-ga I'm adding initGA() function on every component which renders on route response. I think it is not right to duplicate initGA() in every component. Please, guys, how do you use react-ga? What is right way to use react-ga?


回答1:


To make it work need to use Router functionality. So in App component import { Router } from 'react-router-dom'. It has to be Router not BrowserRouter.

Then import createHistory from 'history/createBrowserHistory'

const history = createHistory()
ReactGA.initialize('UA-000000-1');
history.listen((location, action) => {
    ReactGA.pageview(location.pathname + location.search);
    console.log(location.pathname)
});

This code will fire on every route change!

Than give a history attribute to your Router component.

Complete code:

import React, { Component } from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory'
import Main from './components/pages/Main';
import ReactGA from 'react-ga';


const history = createHistory()
ReactGA.initialize('UA-00000000-1');
history.listen((location, action) => {
    ReactGA.pageview(location.pathname + location.search);
    console.log(location.pathname)
});

class App extends Component {

    render() {
        return (

            <Router history={history}>
                <div className="App">

                    <Switch>
                        <Route exact path="/" component={Main} />
                        <Route exact path="/signup" component={SignupLayout} />
                        <Route component={PublicLayout} />
                    </Switch>

                </div>
            </Router>
        );
    }
}

export default App;



回答2:


You should only init once, and then after that use

ReactGA.pageview(pagepath);

in your routing.

Demo: https://github.com/react-ga/react-ga/tree/master/demo




回答3:


This is the way to do it with hooks.

App.js

import React, { useEffect } from 'react
import { Router, Route } from 'react-router-dom'
import { createBrowserHistory } from 'history'
import ReactGA from 'react-ga'

ReactGA.initialize(process.env.REACT_APP_GA_TRACKING_NO)
const browserHistory = createBrowserHistory()
browserHistory.listen((location, action) => {
  ReactGA.pageview(location.pathname + location.search)
})

const App = () => {
  useEffect(() => {
    ReactGA.pageview(window.location.pathname + window.location.search)
  }, [])

  return <div>Test</div>
}

The answer above with the class components is almost fine, but you won't get to see the first page load in the analytics. The history.listen will fire only when the route changes. This doesn't happen when you first load the page. To fix this, I added a useEffect a hook in the App component. If the user reloads the site, the App will be always rerendered. ReactGA.pageview(window.location.pathname + window.location.search) makes sure that we attribute the reload to the correct route if the route is something else than '/'.



来源:https://stackoverflow.com/questions/52724447/how-to-use-google-analytics-with-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!