Google Analytics com roteador react e react

Nov 02 2020

Tenho tentado integrar o Google Analytics em meu aplicativo de reação e usei todas as maneiras mencionadas neste tópico e todas as soluções estão falhando. Abaixo estão os métodos que tentei e o erro correspondente que estou recebendo. Espero que alguém possa ajudar

import React, { Fragment } from 'react';
import store from './Store';
import { Router, Route, Switch } from 'react-router-dom';
import { Provider } from 'react-redux';
import Navbar from './components/layout/Navbar';
import Login from './components/auth/Login';
import Footer from './components/layout/Footer';
import MobileMenu from './components/layout/MobileMenu';
import Tutorial from './components/layout/Tutorial';
import ReactGA from 'react-ga';
import { createBrowserHistory } from 'history';

const history = createBrowserHistory();
ReactGA.initialize('G-11111111');
history.listen((location, action) => {
  ReactGA.pageview(location.pathname + location.search);
  console.log(location.pathname);
});
const App = () => {
  return (
    <div className="App">
      <Provider store={store}>
        <MuiThemeProvider theme={theme}>
          <Router history={history}>
            <Fragment>
              <Navbar />
              <Switch>
                <Route exact path="/" component={Login} />
                <Route exact path="/tutorial" component={Tutorial} />
              </Switch>
              <MobileMenu />
              <Footer />
            </Fragment>
          </Router>
        </MuiThemeProvider>
      </Provider>
    </div>
  );
};

export default App;

A primeira página carrega normalmente, mas se eu clicar em qualquer link do meu switch, recebo uma página em branco e o seguinte aviso

react_devtools_backend.js:2450 [react-ga] path is required in .pageview()

Segundo método que tentei com ganchos, recebo o mesmo erro

import React, { Fragment, useEffect } from 'react';
import store from './Store';
import { Router, Route, Switch } from 'react-router-dom';
import { Provider } from 'react-redux';
import Navbar from './components/layout/Navbar';
import Login from './components/auth/Login';
import Footer from './components/layout/Footer';
import MobileMenu from './components/layout/MobileMenu';
import Tutorial from './components/layout/Tutorial';
import ReactGA from 'react-ga';
import { createBrowserHistory } from 'history';


const history = createBrowserHistory();
ReactGA.initialize('G-11111111');

history.listen((location, action) => {
  ReactGA.pageview(location.pathname + location.search);
});

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

  return (
    <div className="App">
      <Provider store={store}>
        <MuiThemeProvider theme={theme}>
          <Router history={history}>
            <Fragment>
              <Navbar />
              <Switch>
                <Route exact path="/" component={Login} />
                <Route exact path="/tutorial" component={Tutorial} />
              </Switch>
              <MobileMenu />
              <Footer />
            </Fragment>
          </Router>
        </MuiThemeProvider>
      </Provider>
    </div>
  );
};

export default App;

Terceira maneira, tentei usar useLocation () e nenhum histórico

import React, { Fragment, useEffect } from 'react';
import store from './Store';
import {
  BrowserRouter as Router,
  Route,
  Switch,
  useLocation
} from 'react-router-dom';
import { Provider } from 'react-redux';
import Navbar from './components/layout/Navbar';
import Login from './components/auth/Login';
import Footer from './components/layout/Footer';
import MobileMenu from './components/layout/MobileMenu';
import Tutorial from './components/layout/Tutorial';
import ReactGA from 'react-ga';
import { createBrowserHistory } from 'history';



const history = createBrowserHistory();
ReactGA.initialize('G-11111111');


const App = () => {
  const location = useLocation();

  // Fired on every route change
  useEffect(() => {
    ReactGA.pageview(location.pathname + location.search);
  }, [location]);


  return (
    <div className="App">
      <Provider store={store}>
        <MuiThemeProvider theme={theme}>
          <Router history={history}>
            <Fragment>
              <Navbar />
              <Switch>
                <Route exact path="/" component={Login} />
                <Route exact path="/tutorial" component={Tutorial} />
              </Switch>
              <MobileMenu />
              <Footer />
            </Fragment>
          </Router>
        </MuiThemeProvider>
      </Provider>
    </div>
  );
};

export default App;

Eu obtenho o seguinte erro

TypeError: Cannot read property 'location' of undefined

Respostas

1 MichelePisani Nov 02 2020 at 13:49

Provavelmente, depende se você está usando um ID de propriedade do Google Analytics 4 (G-XXXXXXXX), enquanto o pacote React Analytics em questão funciona para o Universal Analytics. Sugiro que você crie uma propriedade do Universal Analytics (conforme mostrado na imagem a seguir) e use o identificador relativo UA-XXXXXXX-X: