How to add Google Analytics to the React App?

Today we will learn about how to adding add Google Analytics to the React App use. To implement faster, we will use a useful package called react-ga

Install package:

npm install react-ga --save

// or

yarn add react-ga


Initialization:

import ReactGA from 'react-ga';

ReactGA.initialize('UA-000000-01'); // UA-000000-01 replace this with your GA ID
ReactGA.pageview(window.location.pathname + window.location.search);


Initialization with event: ReactGA.event(args)

ReactGA.event({
  category: 'User',
  action: 'Created an Account'
});
 
ReactGA.event({
  category: 'Social',
  action: 'Rated an App',
  value: 3
});
 
ReactGA.event({
  category: 'Editing',
  action: 'Deleted Component',
  label: 'Game Widget'
});
 
ReactGA.event({
  category: 'Promotion',
  action: 'Displayed Promotional Widget',
  label: 'Homepage Thing',
  nonInteraction: true
});


Or with multiple trackers:

ReactGA.initialize(
  [
    {
      trackingId: 'UA-000000-01',
      gaOptions: {
        name: 'tracker1',
        userId: 123
      }
    },
    {
      trackingId: 'UA-000000-02',
      gaOptions: { name: 'tracker2' }
    }
  ],
  { debug: true, alwaysSendToDefaultTracker: false }
);


View more at: https://github.com/react-ga/react-ga


© 2019 4codev

Created with love by Sil.