How to add google analytics to your reactjs app?

Published : 10th April 2020 | by @faisaljebali
#reactjs#google analytics

In this article we will set up analytics tracking in React.js with Google Analytics.

Overview

This article is a guide to add Google Analytics to React App project. We will use an open source library called React-GA. After reading this guide, you’ll be able to track all page views in your Create React App.

If you have a single page app that has no routes, getting visitors tracked with Google Analytics is pretty straight forward using the React Google Analytics Module.

Prerequisites

To begin integrating Google Analytics with your react project, you’ll need to create your tracking ID from https://analytics.google.com/

setup google analytics

Usage with reactjs

Then we need to install the react-ga package.

$ npm install --save react-ga

Import this module at the top of the app: import ReactGA from 'react-ga';

import React from "react"; import ReactGA from "react-ga"; //Google Analytics export default function App() { return ( <div className="App"> <h1>Hello</h1> <h2>Start editing to see some magic happen!</h2> </div> ); }

Next add this code bellow

import React,{useEffect} from "react"; import ReactGA from "react-ga"; //Google Analytics export default function App() { useEffect(() => { ReactGA.initialize('your tracking Id'); ReactGA.pageview(window.location.pathname); }) return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> </div> ); }

If you are using react-router, there is a little more config.you need to install the packages.

$ npm install --save history react-router-dom

Next, we simply need to connect our browser history instance to the router and our Google Analytics tracking.

import React from "react"; import ReactDOM from 'react-dom'; import ReactGA from 'react-ga'; import { createBrowserHistory } from 'history'; import { Router } from 'react-router-dom'; export default function App() { const history = createBrowserHistory(); // Initialize google analytics page view tracking history.listen(location => { ReactGA.initialize('your tracking Id'); ReactGA.set({ page: location.pathname }); // Update the user's current page ReactGA.pageview(location.pathname); // Record a pageview for the given page }); return ( <Router history={history}> <YourAppComponent /> </Router> ); }

Deploy and start watching Google Analytics real time tracking. First go to your site. Next, go to Google Analytics Dashboard, and choose Real-Time > Overview and you will see one active user.

google analytics

Thanks for reading.

Home page