在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):react-ga/react-ga开源软件地址(OpenSource Url):https://github.com/react-ga/react-ga开源编程语言(OpenSource Language):JavaScript 94.9%开源软件介绍(OpenSource Introduction):react-gaReact Google Analytics ModuleThis 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 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 InstallationWith npm: npm install react-ga --save With bower: bower install react-ga --save Note that React >= 0.14.0 is needed in order to use the UsageWith npmInitializing GA and Tracking Pageviews: import ReactGA from 'react-ga';
ReactGA.initialize('UA-000000-01');
ReactGA.pageview(window.location.pathname + window.location.search); With bowerWhen included as a script tag, a variable <!-- The core React library -->
<script src="https://unpkg.com/[email protected]/dist/react.min.js"></script>
<!-- The ReactDOM Library -->
<script src="https://unpkg.com/[email protected]/dist/react-dom.min.js"></script>
<!-- ReactGA library -->
<script src="/path/to/bower_components/react-ga/dist/react-ga.min.js"></script>
<script>
ReactGA.initialize('UA-000000-01', { debug: true });
</script> Demo CodeFor a working demo have a look at the demo files or clone this repo and run
Upgrading from |
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.
ReactGA.set({ dimension14: 'Sports' });
Or with multiple trackers
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('/about/contact-us');
Or with multiple trackers
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
.
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.
ReactGA.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.
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'. |
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:
ReactGA.timing({
category: 'JS Libraries',
variable: 'load',
value: 20, // in milliseconds
label: 'CDN libs'
});
This is equivalent to the following Google Analytics command:
ga('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:
ReactGA.ga('send', 'pageview', '/mypage');
Usage without arguments:
var ga = ReactGA.ga();
ga('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.
ReactGA.outboundLink(
{
label: 'Clicked Create an Account'
},
function () {
console.log('redirect here');
},
['tracker2']
);
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.
var ReactGA = require('react-ga');
render() {
return (
<div>
<ReactGA.OutboundLink
eventLabel="myLabel"
to="http://www.example.com"
target="_blank"
trackerNames={['tracker2']}
>
My Link
</ReactGA.OutboundLink>
</div>
);
}
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.
ReactGA.exception({
description: 'An error occurred',
fatal: true
});
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.
ReactGA.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.
ReactGA.plugin.execute('ecommerce', 'addTransaction', {
id: 'jd38je31j',
revenue: '3.50'
});
You can use this function with four arguments to pass actionType
and payload
along with executed action
ReactGA.plugin.execute('ec', 'setAction', 'purchase', {
id: 'jd38je31j',
revenue: '3.50'
});
To enable test mode, initialize ReactGA with the testMode: true
option. Here's an example from tests/utils/testMode.test.js
// This should be part of your setup
ReactGA.initialize('foo', { testMode: true });
// This would be in the component/js you are testing
ReactGA.ga('send', 'pageview', '/mypage');
// This would be how you check that the calls are made correctly
expect(ReactGA.testModeAPI.calls).toEqual([
['create', 'foo', 'auto'],
['send', 'pageview', '/mypage']
]);
To enable standard implemention of google analytics.
Add this script to your html
<!-- Google Analytics -->
<
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论