Thidasa Pankaja
Thidasa Pankaja

Reputation: 1080

Google Analytics on React app doesn't work

I hosted my portfolio (which is still under development) on github pages. It's just a web app with static content. And I needed to add Google Analytics to my portfolio and get the number of visits (mainly to get familiar with the process). I found out react-ga module which can be used to configure Google Analytics on React Apps (which created using create-react-app).

And followed this tutorial and configured it and hosted. And I checked the site with test traffic but Google Analytics dashboard doesn't update. What maybe the case ? It should work according to the tutorial. As I'm new to Google Analytics it's hard for me to figure out the issue.

This is my App.js

import React, { Component } from "react";
import HeaderList from "./components/Header";
import "./App.css";
import { Layout } from "antd";
import { Router, Route, Switch } from "react-router-dom";
import createHistory from "history/createBrowserHistory";
import ReactGA from 'react-ga';
import Keys from './config/keys';

import AboutMe from "./components/AboutMe";
import Skills from "./components/Skills";
import Contact from "./components/Contact";
import Projects from "./components/Projects";

const { Content } = Layout;
ReactGA.initialize(Keys.GOOGLE_TRACKING_ID); //Unique Google Analytics tracking number

function fireTracking() {
  ReactGA.pageview(window.location.hash);
}

class App extends Component {
  render() {
    return (
      <Router onUpdate={fireTracking} history={createHistory({ basename: process.env.PUBLIC_URL })}>
        <div>
          <Layout>
            <HeaderList />
            <Content className="Content">
              <div className="RouteContent">
                <Switch>
                  <Route exact path="/" component={AboutMe} />
                  <Route path="/skills" component={Skills} />
                  <Route path="/projects" component={Projects} />
                  <Route path="/Contact" component={Contact} />
                </Switch>
              </div>
            </Content>
          </Layout>
        </div>
      </Router>
    );
  }
}

export default App;

Upvotes: 0

Views: 7180

Answers (3)

React v16.8 or higher

The pageviews can be generated in a useEffect function; withRouter is used to inject props on route changes:

import React, { useEffect }          from 'react';
import { Switch, Route, withRouter } from 'react-router-dom';
import ReactGA                       from 'react-ga';
import Keys                          from './config/keys';

//Unique Google Analytics tracking number
ReactGA.initialize(Keys.GOOGLE_TRACKING_ID); 

const App = () => {

    useEffect( () => {

        // This line will trigger on a route change
        ReactGA.pageview(window.location.pathname + window.location.search); 

    });

    return (/* Code here */);

}

export default withRouter(App);

Prior to React v16.8

You need to generate a pageview in componentDidMount and componentDidUpdate:

componentDidMount  = () => ReactGA.pageview(window.location.pathname + window.location.search);
componentDidUpdate = () => ReactGA.pageview(window.location.pathname + window.location.search);

So, final code:

import React, { Component } from "react";
import HeaderList from "./components/Header";
import "./App.css";
import { Layout } from "antd";
import { Router, Route, Switch } from "react-router-dom";
import createHistory from "history/createBrowserHistory";
import ReactGA from 'react-ga';
import Keys from './config/keys';

import AboutMe from "./components/AboutMe";
import Skills from "./components/Skills";
import Contact from "./components/Contact";
import Projects from "./components/Projects";

const { Content } = Layout;
ReactGA.initialize(Keys.GOOGLE_TRACKING_ID); //Unique Google Analytics tracking number

class App extends Component {

  componentDidMount  = () => ReactGA.pageview(window.location.pathname + window.location.search);
  componentDidUpdate = () => ReactGA.pageview(window.location.pathname + window.location.search);

  render() {
    return (
      <Router>
        <div>
          <Layout>
            <HeaderList />
            <Content className="Content">
              <div className="RouteContent">
                <Switch>
                  <Route exact path="/" component={AboutMe} />
                  <Route path="/skills" component={Skills} />
                  <Route path="/projects" component={Projects} />
                  <Route path="/Contact" component={Contact} />
                </Switch>
              </div>
            </Content>
          </Layout>
        </div>
      </Router>
    );
  }
}

export default App;

Upvotes: 11

William
William

Reputation: 83

If you’re interested in tracking page visits (and user behavior down the road), I suggest using the Segment analytics library and following our React quickstart guide to track page calls using the react-router library. You can allow the <Route /> component to handle when the page renders and use componentDidMount to invoke page calls. The example below shows one way you could do this:

const App = () => (
  <div>
    <Switch>
       <Route exact path="/" component={Home} />
       <Route path="/about" component={About} />
    </Switch>
  </div>
);

export default App;
export default class Home extends Component {
  componentDidMount() {
    window.analytics.page('Home');
  }

  render() {
    return (
      <h1>
        Home page.
      </h1>
    );
  }
}

I’m the maintainer of https://github.com/segmentio/analytics-react. With Segment, you’ll be able to switch different destinations on-and-off by the flip of a switch if you are interested in trying multiple analytics tools (we support over 250+ destinations) without having to write any additional code. 🙂

Upvotes: 0

Tom
Tom

Reputation: 2954

Unfortunately onUpdate was removed in React Router v4, which means your fireTracking function never fires.

In the react-ga documentation there's an example from Julia Giu that has been included for exactly this scenario which involves wrapping your application in an HoC.

Upvotes: 0

Related Questions