Gathering detailed insights and metrics for react-ga
Gathering detailed insights and metrics for react-ga
Gathering detailed insights and metrics for react-ga
Gathering detailed insights and metrics for react-ga
npm install react-ga
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
5,126 Stars
373 Commits
445 Forks
74 Watching
11 Branches
82 Contributors
Updated on 06 Nov 2024
Minified
Minified + Gzipped
JavaScript (94.71%)
TypeScript (5.12%)
Shell (0.17%)
Cumulative downloads
Total Downloads
Last day
-7.6%
57,843
Compared to previous day
Last week
2.9%
308,353
Compared to previous week
Last month
8%
1,276,461
Compared to previous month
Last year
-27%
16,004,343
Compared to previous year
2
41
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.
With npm:
1npm install react-ga --save
With bower:
1bower install react-ga --save
Note that React >= 0.14.0 is needed in order to use the <OutboundLink>
component.
Initializing GA and Tracking Pageviews:
1import ReactGA from 'react-ga'; 2ReactGA.initialize('UA-000000-01'); 3ReactGA.pageview(window.location.pathname + window.location.search);
When included as a script tag, a variable ReactGA
is exposed in the global scope.
1 2<!-- The core React library --> 3<script src="https://unpkg.com/react@15.5.0/dist/react.min.js"></script> 4<!-- The ReactDOM Library --> 5<script src="https://unpkg.com/react-dom@15.5.0/dist/react-dom.min.js"></script> 6<!-- ReactGA library --> 7<script src="/path/to/bower_components/react-ga/dist/react-ga.min.js"></script> 8 9<script> 10 ReactGA.initialize('UA-000000-01', { debug: true }); 11</script>
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.
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.
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.
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.
1ReactGA.initialize('UA-000000-01', { 2 debug: true, 3 titleCase: false, 4 gaOptions: { 5 userId: 123 6 } 7});
Or with multiple trackers
1ReactGA.initialize( 2 [ 3 { 4 trackingId: 'UA-000000-01', 5 gaOptions: { 6 name: 'tracker1', 7 userId: 123 8 } 9 }, 10 { 11 trackingId: 'UA-000000-02', 12 gaOptions: { name: 'tracker2' } 13 } 14 ], 15 { debug: true, alwaysSendToDefaultTracker: false } 16);
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.
This will set the values of custom dimensions in Google Analytics.
1ReactGA.set({ dimension14: 'Sports' });
Or with multiple trackers
1ReactGA.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 |
1ReactGA.pageview('/about/contact-us');
Or with multiple trackers
1ReactGA.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
.
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.
1ReactGA.modalview('/about/contact-us');
Value | Notes |
---|---|
modalName | String . E.g. 'login', 'read-terms-and-conditions' |
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.
1ReactGA.event({ 2 category: 'User', 3 action: 'Created an Account' 4}); 5 6ReactGA.event({ 7 category: 'Social', 8 action: 'Rated an App', 9 value: 3 10}); 11 12ReactGA.event({ 13 category: 'Editing', 14 action: 'Deleted Component', 15 label: 'Game Widget' 16}); 17 18ReactGA.event({ 19 category: 'Promotion', 20 action: 'Displayed Promotional Widget', 21 label: 'Homepage Thing', 22 nonInteraction: true 23});
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'. |
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.
Usage:
1ReactGA.timing({ 2 category: 'JS Libraries', 3 variable: 'load', 4 value: 20, // in milliseconds 5 label: 'CDN libs' 6});
This is equivalent to the following Google Analytics command:
1ga('send', 'timing', 'JS Libraries', 'load', 20, 'CDN libs');
Value | Notes |
---|---|
args.category | String . Required. A string for categorizing all user timing variables into logical groups. |
args.variable | String . Required. Name of the variable being recorded. |
args.value | Int . Required. Number of milliseconds elapsed time to report. |
args.label | String . Optional. It can be used to add flexibility in visualizing user timings in the reports. |
The original ga
function can be accessed via this method. This gives developers the flexibility of directly
using ga.js
features that have not yet been implemented in ReactGA
. No validations will be done
by ReactGA
as it is being bypassed if this approach is used.
If no arguments are passed to ReactGA.ga()
, the ga
object is returned instead.
Usage with arguments:
1ReactGA.ga('send', 'pageview', '/mypage');
Usage without arguments:
1var ga = ReactGA.ga(); 2ga('send', 'pageview', '/mypage');
Tracking links out to external URLs (including id.webmaker.org for OAuth 2.0 login flow). A declarative approach is found in the next section, by using an <OutboundLink>
component.
1ReactGA.outboundLink( 2 { 3 label: 'Clicked Create an Account' 4 }, 5 function () { 6 console.log('redirect here'); 7 }, 8 ['tracker2'] 9);
Value | Notes |
---|---|
args.label | String . Required. Description of where the outbound link points to. Either as a URL, or a string. |
hitCallback | function . The react-ga implementation accounts for the possibility that GA servers are down, or GA is blocked, by using a fallback 250ms timeout. See notes in GA Dev Guide |
trackerNames | Array<String> Optional. A list of extra trackers to run the command on. |
<OutboundLink>
ComponentOutbound links can directly be used as a component in your React code and the event label will be sent directly to ReactGA.
1var ReactGA = require('react-ga'); 2 3render() { 4 return ( 5 <div> 6 <ReactGA.OutboundLink 7 eventLabel="myLabel" 8 to="http://www.example.com" 9 target="_blank" 10 trackerNames={['tracker2']} 11 > 12 My Link 13 </ReactGA.OutboundLink> 14 </div> 15 ); 16}
Value | Notes |
---|---|
eventLabel | String . Required. Description of where the outbound link points to. Either as a URL, or a string. |
to | String . Required. URL the link leads to. |
target | String . Optional. To open the link in a new tab, use a value of _blank . |
trackerNames | Array<String> Optional. A list of extra trackers to run the command on. |
For bower, use the <ReactGA.OutboundLink>
component.
1ReactGA.exception({ 2 description: 'An error occurred', 3 fatal: true 4});
Value | Notes |
---|---|
args.description | String . Optional. Description of what happened. |
args.fatal | boolean . Optional. Set to true if it was a fatal exception. |
Require GA plugins.
1ReactGA.plugin.require('localHitSender', { path: '/log', debug: true });
Value | Notes |
---|---|
name | String . Required. The name of the plugin to be required. Note: if the plugin is not an official analytics.js plugin, it must be provided elsewhere on the page. |
options | Object . Optional. An initialization object that will be passed to the plugin constructor upon instantiation. |
Execute the action
for the pluginName
with the payload.
1ReactGA.plugin.execute('ecommerce', 'addTransaction', { 2 id: 'jd38je31j', 3 revenue: '3.50' 4});
You can use this function with four arguments to pass actionType
and payload
along with executed action
1ReactGA.plugin.execute('ec', 'setAction', 'purchase', { 2 id: 'jd38je31j', 3 revenue: '3.50' 4});
To enable test mode, initialize ReactGA with the testMode: true
option. Here's an example from tests/utils/testMode.test.js
1// This should be part of your setup 2ReactGA.initialize('foo', { testMode: true }); 3// This would be in the component/js you are testing 4ReactGA.ga('send', 'pageview', '/mypage'); 5// This would be how you check that the calls are made correctly 6expect(ReactGA.testModeAPI.calls).toEqual([ ['create', 'foo', 'auto'], 7 ['send', 'pageview', '/mypage'] 8]);
To enable standard implemention of google analytics.
Add this script to your html
1<!-- Google Analytics --> 2<script> 3 (function (i, s, o, g, r, a, m) { 4 i['GoogleAnalyticsObject'] = r; 5 (i[r] = 6 i[r] || 7 function () { 8 (i[r].q = i[r].q || []).push(arguments); 9 }), 10 (i[r].l = 1 * new Date()); 11 (a = s.createElement(o)), (m = s.getElementsByTagName(o)[0]); 12 a.async = 1; 13 a.src = g; 14 m.parentNode.insertBefore(a, m); 15 })( 16 window, 17 document, 18 'script', 19 '<%=htmlWebpackPlugin.options.analyticsURL%>', 20 'ga' 21 ); 22 ga('create', 'UA-XXX-X', 'auto'); 23 ga('send', 'pageview'); 24</script> 25<!-- End Google Analytics -->
Initialize ReactGA with standardImplementation: true
option.
1// This should be part of your setup 2ReactGA.initialize('UA-XXX-X', { standardImplementation: true });
npm install
npm install react@^15.6.1 prop-types@^15.5.10
- This is for the optional dependencies.1npm test
Follow instructions inside CONTRIBUTING.md
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 12/26 approved changesets -- score normalized to 4
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
Reason
project is archived
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
46 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn Morereact-ga-gtm
React Google Analytics Module.
react-ga4
React Google Analytics 4
insight
Understand how your tool is being used by anonymously reporting usage metrics to Google Analytics or Yandex.Metrica
react-ga-donottrack
Wrapper for react-ga that only adds Google Analytics if DoNotTrack is not enabled