idehub/react-native-google-analytics-bridge

Name: react-native-google-analytics-bridge

Owner: Idéhub

Description: React Native bridge to the Google Analytics libraries on both iOS and Android.

Created: 2015-11-28 13:02:55.0

Updated: 2018-01-20 04:21:13.0

Pushed: 2018-01-18 09:01:34.0

Homepage:

Size: 46356

Language: Objective-C

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

GoogleAnalyticsBridge npm version Build Status

Google Analytics Bridge is built to provide an easy interface to the native Google Analytics libraries on both iOS and Android.

Why a native bridge? Why not use just JavaScript?

The key difference with the native bridge is that you get a lot of the metadata handled automatically by the Google Analytics native library. This will include the device UUID, device model, viewport size, OS version etc.

You will only have to send in a few parameteres when tracking, e.g:

rt { GoogleAnalyticsTracker } from "react-native-google-analytics-bridge";
tracker = new GoogleAnalyticsTracker("UA-12345-1");

ker.trackScreenView("Home");
ker.trackEvent("testcategory", "testaction");
Problems with tracking? Visitors not showing up?

This is NOT (normally) an error with this library. Please read this guide on how to set up your Google Analytics account/property for mobile analytics.

Content
Installation and linking libraries

Install with npm: npm install --save react-native-google-analytics-bridge

Or, install with yarn: yarn add react-native-google-analytics-bridge

Either way, then link with: react-native link react-native-google-analytics-bridge

If it doesn't work immediately after this, consult the manual installation guide. Both Android and iOS has a couple of prerequisite SDKs linked and installed.

Important: Does this library work with Expo? We have to sort of invert the question a bit, because it should be: does Expo work with other libraries? And the answer is no:

The most limiting thing about Expo is that you can?t add in your own native modules without detaching and using ExpoKit.

This includes using create-react-native-app which also makes use of Expo.

Usage
ou have access to three classes in this module:
rt {
ogleAnalyticsTracker,
ogleTagManager,
ogleAnalyticsSettings
om "react-native-google-analytics-bridge";

he tracker must be constructed, and you can have multiple:
tracker1 = new GoogleAnalyticsTracker("UA-12345-1");
tracker2 = new GoogleAnalyticsTracker("UA-12345-2");

ker1.trackScreenView("Home");
ker1.trackEvent("Customer", "New");

he GoogleAnalyticsSettings is static, and settings are applied across all trackers:
leAnalyticsSettings.setDispatchInterval(30);
etting `dryRun` to `true` lets you test tracking without sending data to GA
leAnalyticsSettings.setDryRun(true);

oogleTagManager is also static, and works only with one container. All functions here are Promises:
leTagManager.openContainerWithId("GT-NZT48")
hen(() => {
return GoogleTagManager.stringForKey("pack");

hen(pack => {
console.log("Pack: ", pack);

atch(err => {
console.log(err);
;
Providing an existing GTM container

In some scenarios it might be helpful to provide an opened GTM container to the bridge. Some possible scenarios where this could be helpful:

This will require that you are familiar with the native api for GTM on whatever platforms you want to support. Generally the process is to load your container at startup, and hold the creation of the react native bridge until the container is loaded. On iOS you can then initialize an RCTGoogleTagManagerBridge and set the container property. On Android the process is similar, but you will need to supply the ContainerHolder to the GoogleAnalyticsBridgePackage instead.

JavaScript API
GoogleAnalyticsTracker API
new GoogleAnalyticsTracker(trackerId, customDimensionsFieldsIndexMap = {})
rt { GoogleAnalyticsTracker } from "react-native-google-analytics-bridge";
tracker = new GoogleAnalyticsTracker("UA-12345-1");

Google Analytics expects dimensions to be tracked by indices, and not field names. To simplify this, you can construct a tracker with a customDimensionsFieldsIndexMap. With this, you can map field names to indices, e.g:

tracker2 = new GoogleAnalyticsTracker("UA-12345-3", { test: 1 });
ker2.trackScreenViewWithCustomDimensionValues("Home", { test: "Beta" });

Here the underlying logic will transform the custom dimension, so what ends up being sent to GA is { 1: 'Beta' }. This should make it easier to use custom dimensions. If you do not provide a customDimensionsFieldsIndexMap, the custom dimensions are passed through untouched.

trackScreenView(screenName)

Important: Calling this will also set the “current view” for other calls. So events tracked will be tagged as having occured on the current view, Home in this example. This means it is important to track navigation, especially if events can fire on different views.

See the Google Analytics docs for more info

ker.trackScreenView("Home");
trackEvent(category, action, optionalValues)

See the Google Analytics docs for more info.

ker.trackEvent("testcategory", "testaction");
r
ker.trackEvent("testcategory", "testaction", {
bel: "v1.0.3",
lue: 22

trackTiming(category, value, optionalValues)

See the Google Analytics docs for more info.

ker.trackTiming("testcategory", 13000, { name: "LoadList" }); // name option is required
r
ker.trackTiming("testcategory", 13000, {
me: "loadList",
bel: "v1.0.3"

trackPurchaseEvent(product, transaction, eventCategory, eventAction)

See the Google Analytics docs for more info.

ker.trackPurchaseEvent(

id: "P12345",
name: "Android Warhol T-Shirt",
category: "Apparel/T-Shirts",
brand: "Google",
variant: "Black",
price: 29.2,
quantity: 1,
couponCode: "APPARELSALE"


id: "T12345",
affiliation: "Google Store - Online",
revenue: 37.39,
tax: 2.85,
shipping: 5.34,
couponCode: "SUMMER2013"

commerce",
urchase"

trackMultiProductsPurchaseEvent(products, transaction, eventCategory, eventAction)

same as trackPurchaseEvent but instead of one product you can provide an Array of products

trackMultiProductsPurchaseEventWithCustomDimensionValues(products, transaction, eventCategory, eventAction, dimensionIndexValueDict)
ker.trackMultiProductsPurchaseEventWithCustomDimensionValues(

{
  id: "P12345",
  name: "Android Warhol T-Shirt",
  category: "Apparel/T-Shirts",
  brand: "Google",
  variant: "Black",
  price: 29.2,
  quantity: 1,
  couponCode: "APPARELSALE"
},
{
  id: "P54321",
  name: "IOS T-Shirt",
  category: "Apparel/T-Shirts",
  brand: "Apple",
  variant: "Black",
  price: 10.1,
  quantity: 1,
  couponCode: "APPARELSALE"
}


id: "T12345",
affiliation: "Store - Online",
revenue: 52.5,
tax: 7.86,
shipping: 5.34,
couponCode: "SUMMER2013"

commerce",
urchase",
"1": "premium", "5": "foo" }

trackException(error, fatal)

See the Google Analytics docs for more info.

{
.
tch(error) {
acker.trackException(error.message, false);

trackSocialInteraction(network, action, targetUrl)

See the Google Analytics docs for more info.

ker.trackSocialInteraction("Twitter", "Post");
trackScreenViewWithCustomDimensionValues(screenName, dimensionIndexValueDict)

Tracks a screen view with one or more customDimensionValues. See the Google Analytics docs for more info.

ker.trackScreenViewWithCustomDimensionValues("Home", {
": "premium",
": "foo"

trackEventWithCustomDimensionValues(category, action, optionalValues, dimensionIndexValueDict)

Tracks an event with one or more customDimensionValues. See the Google Analytics docs for more info.

ker.trackEventWithCustomDimensionValues(
estcategory",
estaction",
label: "v1.0.3", value: 22 },
"1": "premium", "5": "foo" }

trackEventWithCustomDimensionAndMetricValues(category, action, optionalValues, dimensionIndexValueDict)

Tracks an event with one or more customDimensionValues and one or more customMetricValues. See the Google Analytics docs for more info.

ker.trackEventWithCustomDimensionAndMetricValues('testcategory', 'testaction', {label: 'v1.0.3', value: 22}, {'1':'premium', '5':'foo'}, , {'1': 3, '5': 4});
setUser(userId)

See the Google Analytics for more info.

ker.setUser("12345678");
setClient(clientId)

See the Google Analytics for more info.

ker.setClient("35009a79-1a05-49d7-b876-2b884d0f825b");
createNewSession(screenName)

See the Google Analytics for more info.

ker.createNewSession("HomeScreen");
allowIDFA(enabled)

Also called advertising identifier collection, and is used for advertising features.

Important: For iOS you can only use this method if you have done the optional step 6 from the installation guide. Only enable this (and link the appropriate libraries) if you plan to use advertising features in your app, or else your app may get rejected from the AppStore.

See the Google Analytics for more info.

ker.allowIDFA(true);
setTrackUncaughtExceptions(enabled)

Sets if uncaught exceptions should be tracked. This is enabled by default.

ker.setTrackUncaughtExceptions(true);
setAnonymizeIp(enabled)

Sets if AnonymizeIp is enabled. This is disabled by default. If enabled the last octet of the IP address will be removed.

ker.setAnonymizeIp(true);
setAppName(appName)

Overrides the app name logged in Google Analytics. The Bundle name is used by default. Note: This has to be set each time the App starts.

ker.setAppName("someAppName");
setSamplingRate(ratio)

Sets tracker sampling rate.

ker.setSamplingRate(50);
setCurrency(currencyCode)

Sets tracker currency property, see Currency Codes.

ker.setCurrency("EUR");
dispatch()

This function lets you manually dispatch all hits which are queued. Use this function sparingly, as it will normally happen automatically as a batch.

ker.dispatch().then(done => console.log("Dispatch is done: ", done));
dispatchWithTimeout()

The same as dispatch(), but also gives you the ability to time out the Promise in case dispatch takes too long.

ker
ispatchWithTimeout(10000)
hen(done => console.log("Dispatch is done: ", done));
GoogleAnalyticsSettings API

Settings are applied across all trackers.

setDryRun(enabled)

When enabled the native library prevents any data from being sent to Google Analytics. This allows you to test or debug the implementation, without your test data appearing in your Google Analytics reports.

leAnalyticsSettings.setDryRun(true);
setDispatchInterval(intervalInSeconds)

Events, screen views, etc, are sent in batches to your tracker. This function allows you to configure how often (in seconds) the batches are sent to your tracker. Recommended to keep this around 20-120 seconds to preserve battery and network traffic. This is set to 20 seconds by default.

leAnalyticsSettings.setDispatchInterval(30);
setOptOut(enabled)

Sets if OptOut is active and disables Google Analytics. This is disabled by default. Note: This has to be set each time the App starts.

leAnalyticsSettings.setOptOut(true);
GoogleTagManager API
rt { GoogleTagManager } from "react-native-google-analytics-bridge";
leTagManager.openContainerWithId("GT-NZT48")
hen(() => GoogleTagManager.stringForKey("pack"))
hen(str => console.log("Pack: ", str));

Can only be used with one container. All methods returns a Promise.

openContainerWithId(containerId)

Important: Call once to open the container for all subsequent static calls.

leTagManager.openContainerWithId('GT-NZT48')
n((..) => ..)
stringForKey(key)
Parameter(s) Returns:

Retrieves a string with the given key from the opened container.

leTagManager.stringForKey("key").then(val => console.log(val));
boolForKey(key)
Parameter(s) Returns:

Retrieves a boolean value with the given key from the opened container.

leTagManager.boolForKey("key").then(val => console.log(val));
doubleForKey(key)
Parameter(s) Returns:

Retrieves a number with the given key from the opened container.

leTagManager.doubleForKey("key").then(val => console.log(val));
pushDataLayerEvent(dictionary = {})
Parameter(s) Returns:

Push a DataLayer event for Google Analytics through Google Tag Manager.

leTagManager.pushDataLayerEvent({
ent: "eventName",
geId: "/home"
hen(success => console.log(success));
setVerboseLoggingEnabled(enabled)
Parameter(s) Returns:

Sets logger to verbose, default is warning

leTagManager.setVerboseLoggingEnabled(true);

This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.