Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

react-ga

> 前端框架
Open source

React Google Analytics Module

5.1K stars0 likes3 views
WebsiteGitHub

About

React Google Analytics Module

react-ga

React Google Analytics Module

This is a JavaScript module that can be used to include Google Analytics tracking code in a website or app that uses React for its front-end codebase. It does not currently use any React code internally, but has been written for use with a number of Mozilla Foundation websites that are using React, as a way to standardize our GA Instrumentation across projects.

It is designed to work with Universal Analytics and will not support the older ga.js implementation.

This module is mildly opinionated in how we instrument tracking within our front-end code. Our API is slightly more verbose than the core Google Analytics library, in the hope that the code is easier to read and understand for our engineers. See examples below.

If you use react-ga too, we'd love your feedback. Feel free to file issues, ideas and pull requests against this repo.

Installation

With npm:

bash
npm install react-ga --save

With bower:

bash
bower install react-ga --save

Note that React >= 0.14.0 is needed in order to use the <OutboundLink> component.

Usage

With npm

Initializing GA and Tracking Pageviews:

javascript
import ReactGA from 'react-ga';
ReactGA.initialize('UA-000000-01');
ReactGA.pageview(window.location.pathname + window.location.search);

With bower

When included as a script tag, a variable ReactGA is exposed in the global scope.

javascript

<script src="https://unpkg.com/[email protected]/dist/react.min.js"></script>

<script src="https://unpkg.com/[email protected]/dist/react-dom.min.js"></script>

<script src="/path/to/bower_components/react-ga/dist/react-ga.min.js"></script>

<script>
  ReactGA.initialize('UA-000000-01', { debug: true });
</script>

Demo Code

For a working demo have a look at the demo files or clone this repo and run npm install npm start then open http://localhost:8080 and follow the instructions. Demo requires you to have your own TrackingID.

Upgrading from 1.x to 2.x

You can safely upgrade to 2.x as there are no breaking changes. The main new feature is that the underlying ga function is now exposed via the property ReactGA.ga. This can be helpful when you need a function that ReactGA doesn't support at the moment. Also, for that reason, it is recommended that you rename your imported value as ReactGA rather than ga so as to distinguish between the React GA wrapper and the original ga function.

Community Components

While some convenience components are included inside the package, some are specific to each application. A community curated list of these is available in the wiki: https://github.com/react-ga/react-ga/wiki/Community-Components. Feel free to add any you have found useful.

API

ReactGA.initialize(gaTrackingID, options)

GA must be initialized using this function before any of the other tracking functions will record any data. The values are checked and sent through to the ga('create', ... call.

If you aren't getting any data back from Page Timings, you may have to add siteSpeedSampleRate: 100 to the gaOptions object. This will send 100% of hits to Google Analytics. By default only 1% are sent.

Example
javascript
ReactGA.initialize('UA-000000-01', {
  debug: true,
  titleCase: false,
  gaOptions: {
    userId: 123
  }
});

Or with multiple trackers

javascript
ReactGA.initialize(
  [
    {
      trackingId: 'UA-000000-01',
      gaOptions: {
        name: 'tracker1',
        userId: 123
      }
    },
    {
      trackingId: 'UA-000000-02',
      gaOptions: { name: 'tracker2' }
    }
  ],
  { debug: true, alwaysSendToDefaultTracker: false }
);
Value Notes
gaTrackingID String. Required. GA Tracking ID like UA-000000-01.
options.debug Boolean. Optional. If set to true, will output additional feedback to the console.
options.titleCase Boolean. Optional. Defaults to true. If set to false, strings will not be converted to title case before sending to GA.
options.gaOptions Object. Optional. GA configurable create only fields.
options.gaAddress String. Optional. If you are self-hosting your analytics.js, you can specify the URL for it here.
options.alwaysSendToDefaultTracker Boolean. Optional. Defaults to true. If set to false and using multiple trackers, the event will not be send to the default tracker.
options.testMode Boolean. Optional. Defaults to false. Enables test mode. See here for more information.
options.standardImplementation Boolean. Optional. Defaults to false. Enables loading GA as google expects it. See here for more information.
options.useExistingGa Boolean. Optional. Skips call to window.ga(), assuming you have manually run it.
options.redactEmail Boolean. Optional. Defaults to true. Enables redacting a email as the string that in "Event Category" and "Event Action".

If you are having additional troubles and setting debug = true shows as working please try using the Chrome GA Debugger Extension. This will help you figure out if your implementation is off or your GA Settings are not correct.

ReactGA.set(fieldsObject)

This will set the values of custom dimensions in Google Analytics.

Example
javascript
ReactGA.set({ dimension14: 'Sports' });

Or with multiple trackers

javascript
ReactGA.set({ userId: 123 }, ['tracker2']);
Value Notes
fieldsObject Object. e.g. { userId: 123 }
trackerNames Array. Optional. A list of extra trackers to run the command on

ReactGA.pageview(path)

Example
javascript
ReactGA.pageview('/about/contact-us');

Or with multiple trackers

javascript
ReactGA.pageview('/about/contact-us', ['tracker2']);

This will send all the named trackers listed in the array parameter. The default tracker will or will not send according to the initialize() setting alwaysSendToDefaultTracker (defaults to true if not provided).

Value Notes
path String. e.g. '/get-involved/other-ways-to-help'
trackerNames Array. Optional. A list of extra trackers to run the command on
title String. Optional. e.g. 'Other Ways to Help'

See example above for use with react-router.

ReactGA.modalview(modalName)

A modal view is often an equivalent to a pageview in our UX, but without a change in URL that would record a standard GA pageview. For example, a 'contact us' modal may be accessible from any page in a site, even if we don't have a standalone 'contact us' page on its own URL. In this scenario, the modalview should be recorded using this function.

Example
javascript
ReactGA.modalview('/about/contact-us');
Value Notes
modalName String. E.g. 'login', 'read-terms-and-conditions'

ReactGA.event(args)

Tracking in-page event interactions is key to understanding the use of any interactive web property. This is how we record user interactions that don't trigger a change in URL.

Examples
javascript
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
});
Value Notes
args.category String. Required. A top level category for these events. E.g. 'User', 'Navigation', 'App Editing', etc.
args.action String. Required. A description of the behaviour. E.g. 'Clicked Delete', 'Added a component', 'Deleted account', etc.
args.label String. Optional. More precise labelling of the related action. E.g. alongside the 'Added a component' action, we could add the name of a component as the label. E.g. 'Survey', 'Heading', 'Button', etc.
args.value Int. Optional. A means of recording a numerical value against an event. E.g. a rating, a score, etc.
args.nonInteraction Boolean. Optional. If an event is not triggered by a user interaction, but instead by our code (e.g. on page load), it should be flagged as a nonInteraction event to avoid skewing bounce rate data.
args.transport String. Optional. This specifies the transport mechanism with which hits will be sent. Valid values include 'beacon', 'xhr', or 'image'.

ReactGA.timing(args)

Allow to measure periods of time such as AJAX requests and resources loading by sending hits using the analytics.js library. For more detailed description, please refer to https://developers.google.com/analytics/devguides/collection/analyticsjs/user-timings.

Example

Usage:

javascript
ReactGA.timing({
  category: 'JS Libraries',
  variable: 'load',
  value: 20, // in milliseconds
  label: 'CDN libs'
});

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

JavaScriptgoogle-analyticsjavascriptreactreact-google-analytics

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架