OutboundLink = function (props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly
. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0;
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (initialState === undefined && this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
_invariant(typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null
', Constructor.displayName || 'ReactCompositeComponent');
this.state = initialState;
}n/a
event = function (args) {
if (typeof ga === 'function') {
// Simple Validation
if (!args || !args.category || !args.action) {
warn('args.category AND args.action are required in event()');
return;
}
// Required Fields
var fieldObject = {
hitType: 'event',
eventCategory: _format(args.category),
eventAction: _format(args.action)
};
// Optional Fields
if (args.label) {
fieldObject.eventLabel = _format(args.label);
}
if (args.hasOwnProperty('value')) {
if (typeof args.value !== 'number') {
warn('Expected `args.value` arg to be a Number.');
} else {
fieldObject.eventValue = args.value;
}
}
if (args.nonInteraction) {
if (typeof args.nonInteraction !== 'boolean') {
warn('`args.nonInteraction` must be a boolean.');
} else {
fieldObject.nonInteraction = args.nonInteraction;
}
}
if (args.transport) {
if (typeof args.transport !== 'string') {
warn('`args.transport` must be a string.');
} else {
if (['beacon', 'xhr', 'image'].indexOf(args.transport) === -1) {
warn('`args.transport` must be either one of these values: `beacon`, `xhr` or `image`');
}
fieldObject.transport = args.transport;
}
}
// Send to GA
this.send(fieldObject);
}
}...
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
```js
ReactGA.event({
...exception = function (args) {
if (typeof ga === 'function') {
// Required Fields
var fieldObject = {
hitType: 'exception'
};
// Optional Fields
if (args.description) {
fieldObject.exDescription = _format(args.description);
}
if (typeof args.fatal !== 'undefined') {
if (typeof args.fatal !== 'boolean') {
warn('`args.fatal` must be a boolean.');
} else {
fieldObject.exFatal = args.fatal;
}
}
// Send to GA
this.send(fieldObject);
}
}...
|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`.|
For bower, use the `<ReactGA.OutboundLink>` component.
#### ReactGA.exception(args)
[GA exception tracking](https://developers.google.com/analytics/devguides/collection/analyticsjs/exceptions)
###### Example
```js
ReactGA.exception({
...ga = function () {
if (arguments.length > 0) {
ga.apply(this, arguments);
if (_debug) {
log('called ga(\'arguments\');');
log('with arguments: ' + JSON.stringify([].slice.apply(arguments)));
}
return;
}
return ga;
}...
|Value|Notes|
|------|-----|
|args.category|`String`. Required. A string for categorizing all user timing variables into logical groups.|
|args.var|`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 improved visibility in user timing reports.|
#### ReactGA.ga()
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.
...initialize = function (gaTrackingID, options) {
if (!gaTrackingID) {
warn('gaTrackingID is required in initialize()');
return;
}
if (options) {
if (options.debug && options.debug === true) {
_debug = true;
}
if (options.titleCase === false) {
_titleCase = false;
}
}
// https://developers.google.com/analytics/devguides/collection/analyticsjs/
// jscs:disable
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments);
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m);
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
// jscs:enable
if (options && options.gaOptions) {
ga('create', gaTrackingID, options.gaOptions);
} else {
ga('create', gaTrackingID, 'auto');
}
}...
var React = require('react');
var ReactDOM = require('react-dom');
var Router = require('react-router');
var routes = require('./routes');
...
var ReactGA = require('react-ga');
ReactGA.initialize('UA-000000-01');
...
function logPageView() {
ReactGA.set({ page: window.location.pathname });
ReactGA.pageview(window.location.pathname);
}
...modalview = function (modalName) {
if (!modalName) {
warn('modalName is required in .modalview(modalName)');
return;
}
modalName = trim(modalName);
modalName = removeLeadingSlash(modalName);
if (modalName === '') {
warn('modalName cannot be an empty string or a single / in .modalview()');
return;
}
if (typeof ga === 'function') {
modalName = trim(modalName);
var path = '/modal/' + modalName;
ga('send', 'pageview', path);
if (_debug) {
log('called ga(\'send\', \'pageview\', path);');
log('with path: ' + path);
}
}
}...
|Value|Notes|
|------|-----|
|path|`String`. e.g. '/get-involved/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
```js
ReactGA.modalview('/about/contact-us');
...outboundLink = function (args, hitCallback) {
if (typeof hitCallback !== 'function') {
warn('hitCallback function is required');
return;
}
if (typeof ga === 'function') {
// Simple Validation
if (!args || !args.label) {
warn('args.label is required in outboundLink()');
return;
}
// Required Fields
var fieldObject = {
hitType: 'event',
eventCategory: 'Outbound',
eventAction: 'Click',
eventLabel: _format(args.label)
};
var safetyCallbackCalled = false;
var safetyCallback = function () {
// This prevents a delayed response from GA
// causing hitCallback from being fired twice
safetyCallbackCalled = true;
hitCallback();
};
// Using a timeout to ensure the execution of critical application code
// in the case when the GA server might be down
// or an ad blocker prevents sending the data
// register safety net timeout:
var t = setTimeout(safetyCallback, 250);
var clearableCallbackForGA = function () {
clearTimeout(t);
if (!safetyCallbackCalled) {
hitCallback();
}
};
fieldObject.hitCallback = clearableCallbackForGA;
// Send to GA
this.send(fieldObject);
} else {
// if ga is not defined, return the callback so the application
// continues to work as expected
setTimeout(hitCallback, 0);
}
}...
Usage without arguments:
```js
var ga = ReactGA.ga();
ga('send', 'pageview', '/mypage');
```
#### ReactGA.outboundLink(args, hitCallback)
Tracking links out to external URLs (including id.webmaker.org for OAuth 2.0 login flow). A non-programmatic approach is found in
the next section, by using an `<OutboundLink>` component.
###### Example
```js
ReactGA.outboundLink({
...pageview = function (path) {
if (!path) {
warn('path is required in .pageview()');
return;
}
path = trim(path);
if (path === '') {
warn('path cannot be an empty string in .pageview()');
return;
}
if (typeof ga === 'function') {
ga('send', 'pageview', path);
if (_debug) {
log('called ga(\'send\', \'pageview\', path);');
log('with path: ' + path);
}
}
}...
...
var ReactGA = require('react-ga');
ReactGA.initialize('UA-000000-01');
...
function logPageView() {
ReactGA.set({ page: window.location.pathname });
ReactGA.pageview(window.location.pathname);
}
var app = document.getElementById('app');
ReactDOM.render(<Router routes={routes} onUpdate={logPageView} />, app);
```
...send = function (fieldObject) {
if (typeof ga === 'function') {
ga('send', fieldObject);
if (_debug) {
log('called ga(\'send\', fieldObject);');
log('with fieldObject: ' + JSON.stringify(fieldObject));
}
}
}n/a
set = function (fieldsObject) {
if (typeof ga === 'function') {
if (!fieldsObject) {
warn('`fieldsObject` is required in .set()');
return;
}
if (typeof fieldsObject !== 'object') {
warn('Expected `fieldsObject` arg to be an Object');
return;
}
if (Object.keys(fieldsObject).length === 0) {
warn('empty `fieldsObject` given to .set()');
}
ga('set', fieldsObject);
if (_debug) {
log('called ga(\'set\', fieldsObject);');
log('with fieldsObject: ' + JSON.stringify(fieldsObject));
}
}
}...
...
var ReactGA = require('react-ga');
ReactGA.initialize('UA-000000-01');
...
function logPageView() {
ReactGA.set({ page: window.location.pathname });
ReactGA.pageview(window.location.pathname);
}
var app = document.getElementById('app');
ReactDOM.render(<Router routes={routes} onUpdate={logPageView} />, app);
```
...timing = function (args) {
if (typeof ga === 'function') {
if (!args || !args.category || !args.variable
|| !args.value || typeof args.value !== 'number') {
warn('args.category, args.variable ' +
'AND args.value are required in timing() ' +
'AND args.value has to be a number');
return;
}
//Required Fields
var fieldObject = {
hitType: 'timing',
timingCategory: _format(args.category),
timingVar: _format(args.variable),
timingValue: args.value
};
if (args.label) {
fieldObject.timingLabel = _format(args.label);
}
this.send(fieldObject);
}
}...
|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',
x27;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
x27;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:
...OutboundLink = function (props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly
. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0;
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (initialState === undefined && this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
_invariant(typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null
', Constructor.displayName || 'ReactCompositeComponent');
this.state = initialState;
}n/a
origTrackLink = function () {
console.warn('ga tracking not enabled');
}n/a
trackLink = function () { [native code] }n/a
eventLabel = function () { [native code] }n/a
componentDidMount = function () {
this.__isMounted = true;
}n/a
componentWillUnmount = function () {
this.__isMounted = false;
}n/a
constructor = function (props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly
. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0;
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (initialState === undefined && this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
_invariant(typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null
', Constructor.displayName || 'ReactCompositeComponent');
this.state = initialState;
}n/a
handleClick = function (e) {
e.preventDefault();
var props = this.props;
var eventMeta = { label: props.eventLabel };
OutboundLink.trackLink(eventMeta, function () {
if (props.target === NEWTAB) {
window.open(props.to, NEWTAB);
} else {
window.location.href = props.to;
}
});
if (props.onClick) {
props.onClick(e);
}
}n/a
render = function () {
var props = assign({}, this.props, {
href: this.props.to,
onClick: this.handleClick
});
delete props.eventLabel;
return React.createElement('a', props);
}...
function logPageView() {
ReactGA.set({ page: window.location.pathname });
ReactGA.pageview(window.location.pathname);
}
var app = document.getElementById('app');
ReactDOM.render(<Router routes={routes} onUpdate={logPageView} />, app);
```
### With bower
When included as a script tag, a variable `ReactGA` is exposed in the global scope.
...1 = function (e) {
e.preventDefault();
var props = this.props;
var eventMeta = { label: props.eventLabel };
OutboundLink.trackLink(eventMeta, function () {
if (props.target === NEWTAB) {
window.open(props.to, NEWTAB);
} else {
window.location.href = props.to;
}
});
if (props.onClick) {
props.onClick(e);
}
}n/a
execute = function () {
var args = Array.prototype.slice.call(arguments);
var pluginName = args[0];
var action = args[1];
var payload;
var actionType;
if (args.length === 3) {
payload = args[2];
} else {
actionType = args[2];
payload = args[3];
}
if (typeof ga === 'function') {
if (typeof pluginName !== 'string') {
warn('Expected `pluginName` arg to be a String.');
} else if (typeof action !== 'string') {
warn('Expected `action` arg to be a String.');
} else {
var command = pluginName + ':' + action;
payload = payload || null;
if (actionType && payload) {
ga(command, actionType, payload);
if (_debug) {
log('called ga(\'' + command + '\');');
log('actionType: "' + actionType + '" with payload: ' + JSON.stringify(payload));
}
} else if (payload) {
ga(command, payload);
if (_debug) {
log('called ga(\'' + command + '\');');
log('with payload: ' + JSON.stringify(payload));
}
} else {
ga(command);
if (_debug) {
log('called ga(\'' + command + '\');');
}
}
}
}
}...
|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.|
#### ReactGA.plugin.execute(pluginName, action, [actionType], [payload])
Execute the `action` for the `pluginName` with the payload.
###### Example
```js
ReactGA.plugin.execute('ecommerce', 'addTransaction', {
...require = function (name, options) {
if (typeof ga === 'function') {
// Required Fields
if (!name) {
warn('`name` is required in .require()');
return;
}
name = trim(name);
if (name === '') {
warn('`name` cannot be an empty string in .require()');
return;
}
// Optional Fields
if (options) {
if (typeof options !== 'object') {
warn('Expected `options` arg to be an Object');
return;
}
if (Object.keys(options).length === 0) {
warn('Empty `options` given to .require()');
}
ga('require', name, options);
if (_debug) {
log('called ga(\'require\', \'' + name + '\', ' + JSON.stringify(options) + ');');
}
return;
} else {
ga('require', name);
if (_debug) {
log('called ga(\'require\', \'' + name + '\');');
}
return;
}
}
}...
|Value|Notes|
|------|-----|
|args.description|`String`. Optional. Description of what happened.|
|args.fatal|`String`. Optional. Set to `true` if it was a fatal exception.|
#### ReactGA.plugin.require(name, [options])
Require GA plugins.
###### Example
```js
ReactGA.plugin.require('localHitSender', { path: '/log', debug: true });
```
...