0

I am trying to connect my personal website made using ReactJS to Google Analytics. I have followed this tutorial but I am still not able to see an active user (when I access the site on local host or when I deploy it using netlify).

Here is my app.js:

import React, {useEffect} from 'react';
import Courses from './containers/Courses/Courses';
import Home from './containers/Home/Home';
import {Route, Switch, Redirect} from 'react-router-dom';
import Layout from './hoc/Layout/Layout';
import About from './containers/About/About';
import ContactPage from './containers/ContactPage/ContactPage';
import Projects from './components/Projects/Projects';
import ReactGa from 'react-ga';


const App = () => {
  
  useEffect(() => {
    document.title = "Dhruv Mittal";
    ReactGa.initialize('UA-XXXXXXXXX-X');
    //Report page view 
    ReactGa.pageview(window.location.pathname + window.location.search);
  }, []);

  let routes = (
    <Switch>
      <Route path="/about" component={About}/>
      <Route path="/projects" component={Projects}/>
      <Route path="/courses" component={Courses}/>
      <Route path="/contact" exact component={ContactPage}/>
      <Route path="/" component={Home}/>
      <Redirect to='/'/>
    </Switch>
  );

  return (
    <div>
      <Layout>
        {routes}
      </Layout>
    </div>
  );

}

export default App;

1 Answers1

0

You are not listening to the location changes. Try this way. Add a component called GAListener, which listen to the location changes of history object.

GaListener.js

import React from 'react';
import ReactGA from 'react-ga';
import { withRouter } from 'react-router-dom';

class GAListener extends React.Component {
  componentDidMount() {
    ReactGA.initialize("UA-XXXXXXXXX-X");
    this.sendPageView(this.props.history.location);
    this.props.history.listen(this.sendPageView);
  }

  sendPageView = location => {
    ReactGA.set({ page: location.pathname });
    ReactGA.pageview(location.pathname);
  };

  render() {
    return this.props.children;
  }
}

export default withRouter(GAListener);

Now wrap your Route components inside GAListener component as follows.

App.js


const App = () => {
  
  let routes = (
  <GAListener>
    <Switch>
      <Route path="/about" component={About}/>
      <Route path="/projects" component={Projects}/>
      <Route path="/courses" component={Courses}/>
      <Route path="/contact" exact component={ContactPage}/>
      <Route path="/" component={Home}/>
      <Redirect to='/'/>
    </Switch>
  </GAListener>
  );

  return (
    <div>
      <Layout>
        {routes}
      </Layout>
    </div>
  );

}

export default App;
uneet7
  • 2,925
  • 7
  • 24
  • 41