1

I have a React app using react-ga package to add a Google Analytics tracker code (UA-123456789-1) to all the routes.

However, when I search the source code of the React app using the Chrome browser, the tracking code cannot be found. Sure enough, the Google Analytics real time view of the tracking code does not show any data when I am visiting the React app.

ReactGA is being initialized in the my App.js containing React Router routes.

import React, { useEffect } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import createHistory from 'history/createBrowserHistory'

import Home from './screens/Home'
import Faq from './screens/Faq';
import 'bootstrap/dist/css/bootstrap.min.css';

import ReactGA from 'react-ga';
ReactGA.initialize('UA-123456789-1')

function App() {
  const history = createHistory();
  
  history.listen(location => {
    ReactGA.set({ page: location.pathname })
    ReactGA.pageview(location.pathname)
  })

  useEffect(() => {
    ReactGA.pageview(window.location.pathname + window.location.search)
  }, [history])
  
  return (
    <React.Fragment>
      <Router>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route exact path="/faq" component={Faq} />
        </Switch>
      </Router>
    </React.Fragment>
  );
}

export default App;

Why is the GA tracking code not added to the React app?

Athena Wisdom
  • 6,101
  • 9
  • 36
  • 60

0 Answers0