Adding analytics to a React Native app

Introduction

In this tutorial, we’re going to look at how to integrate Segment in a React Native app. We’re specifically going to use Google Analytics as the destination for the analytics data that we gather from the app. We’ll also be using Keen IO to inspect and analyze the data.

Adding analytics to a mobile app is a necessary step in order to understand your users better, so you can provide them with a better user experience.

When selecting an analytics tool, it’s important to select one that allows you to save engineering time and marketing effort. One such tool is Segment. They provide you with integrations to analytics and error tracking tools such as Google Analytics, Mixpanel, Sentry, and Rollbar. They also provide integrations to marketing tools such as Mailchimp, OneSignal, and Blueshift. You can visit their integrations page for a full list of supported integrations.

Prerequisites

In order to follow along, you must have basic knowledge of React Native. Knowledge of Google Analytics is helpful but not required.

This tutorial assumes that your computer has the React Native development environment setup. That’s Android Studio for Android and Xcode for iOS. And all the other necessary tools like Watchman and CocoaPods.

Setting up Google Analytics

This section is divided into two sub-sections: one for users who don’t have an existing Google Analytics account, and another for those who have existing accounts. Only read through the guide that applies to you.

New accounts

If you don’t have a Google account yet, go ahead and create one. Next, visit analytics.google.com and sign in with your Google Account. If you don’t have an existing account yet, you’ll be greeted with the following screen. Click on Sign up to start using Google Analytics:

Sign up for Google Analytics

It will then ask you for some information about your project:

New account tracking

Once you’ve filled out all the text fields, click on the Get Tracking ID button. A modal window will pop-up asking you to agree to the terms of service and license agreement. If it returns an error while signing up, select United States as your country even if you live somewhere else. That should solve the error.

Once that’s done, you should be provided with a tracking ID.

Existing accounts

If you have an existing account Google Analytics account, click on the Admin menu at the bottom left of the screen and on the Property column, click on Create Property:

Create property

But instead of selecting Mobile app, you have to select Website. This is because Google has required new properties to use Firebase for mobile app analytics. This requires you to create a Firebase app as an additional step. More importantly, you have to connect Firebase in your Segment account later on. So to keep things simple, we’re going to stick with good old Google Analytics for this tutorial.

Once you’re on the property creation page, enter the details of your app. The Website URL can be your app’s website or company’s website:

Existing account select web option for new property

Once the property is created, you should be provided with a tracking ID. Take note of this as you will be needing it later when you connect to Segment.

Next, create a new view by clicking on the Admin menu and clicking Create View on the third column. This time, select Mobile app and enter your app details:

New view

If at anytime you want to view your tracking ID, go to SettingsProperty Settings and that should show your tracking ID:

Property settings

Setting up Segment

If you haven’t done so already, create a new Segment account. Once you have an account, create a new workspace. Each workspace equates to a single project. A project can have multiple sources and destinations, depending on where the data is coming from (sources) and where you want to put your data (destinations):

New Segment workspace

Next, you need to select the platform that you want to work with. In this case, we’re going to select My Android App. This will serve as your source:

Segment select source

React Native deploys to both Android and iOS devices, we’re selecting Android in this case. If you want to try to add iOS later on, you can do so by adding a new source and select iOS.

Once the source is created, you can now proceed to adding a destination. Click on the Add Destination button:

Browse for detination

Select Google Analytics from the list that shows:

Select destination

Update the settings with the Mobile Tracking ID. This should be the tracking ID you got from the Google Analytics website earlier. Click on Save once you’ve added it:

Add analytics key to Segment

The last step for setting up Segment is to get your write key. You can find that under your Sources. Earlier, we’ve added Android as a source so you can go ahead and select that and view its settings. Once you’re on the settings page, click on the API Keys menu on the left side of the screen. Copy the Write Key as this will be the one that you’re going to need to put in the React Native app later on:

Obtain Segment write key

Creating the app

To give the analytics data some context, I’ve built a very simple app that allows the user to perform some actions so that we can record data while they’re using it.

The app allows the user to view a list of Pokemon. The user can perform three actions to each item:

  • View
  • Bookmark
  • Share

Here’s what the app looks like. Each icon corresponds to the actions mentioned above:

App homepage

You can find the full source code on its GitHub repo.

To keep the focus on analytics, I won’t be walking you through the code of the sample app. I’ll only be explaining the code used for implementing analytics. Few existing code from the sample app will be shown, but it will only be used to provide some context for the analytics code.

Start by creating a new React Native app:

    react-native init RNSegmentAnalytics

Next, clone the repo in another directory:

    git clone https://github.com/anchetaWern/RNSegmentAnalytics.git

Once it’s cloned, copy the src folder and App.js file to the new React Native project you created earlier.

Installing the packages

Next, install the following packages:

    npm install react-native-analytics-segment-io react-native-device-info react-native-vector-icons --save 

Here’s what each package does:

Note that only the first two are relevant to what we’re trying to achieve. react-native-vector-icons is only for aesthetics purposes.

Linking the packages

The three packages require an additional step for linking the native modules. I didn’t have any luck setting up react-native-analytics-segment-io this way, but you should be able to with the other two packages:

1react-native link react-native-device-info
2    react-native link react-native-vector-icons

Once those are linked, the next step is to manually link the react-native-analytics-segment-io package.

Linking on Android

For Android, open the android/settings.gradle file and add the following right before the include ':app``':

1include ':react-native-analytics-segment-io'
2    project(':react-native-analytics-segment-io').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-analytics-segment-io/android')

Next, update the android/app/build.gradle file and include the following under the dependencies:

1compile 'com.segment.analytics.android:analytics:4.3.1'
2    compile project(':react-native-analytics-segment-io')

Once that’s done, your dependencies should look like this:

1dependencies {
2        compile fileTree(dir: "libs", include: ["*.jar"])
3        compile "com.android.support:appcompat-v7:23.0.1"
4        compile "com.segment.analytics.android:analytics:4.3.1" // add this
5        compile "com.facebook.react:react-native:+"  
6        compile project(':react-native-vector-icons')
7        compile project(':react-native-device-info')
8        compile project(':react-native-analytics-segment-io') // add this
9    }

The final step is to implement the package in the android/app/src/main/java/com/rnsegmentanalytics/MainApplication.java file. Add this right after the last import:

    import com.leo_pharma.analytics.AnalyticsPackage;

Then initialize it in the package list:

1@Override
2    protected List<ReactPackage> getPackages() {
3      return Arrays.<ReactPackage>asList(
4          new MainReactPackage(),
5            new VectorIconsPackage(),
6            new AnalyticsPackage(), // add this
7            new RNDeviceInfo()
8      );
9    }

Linking on iOS

By default, a new React Native project doesn’t really come with a Podfile. You can create one by navigating inside the ios directory and executing pod init. This will create the Podfile, update it so it contains the following:

1platform :ios, '9.0'
2    
3    target 'RNSegmentAnalytics' do
4      pod 'Analytics' # add this
5      pod 'Segment-GoogleAnalytics' #add this
6    end

In the above Podfile, we’ve added the Analytics and Segment-GoogleAnalytics pod. Once that’s done, execute pod install to install those pods.

Next, follow the instructions on the project’s README to ensure the build order. Once that’s done, click the Play button on Xcode or execute react-native run-ios on your terminal to run the app.

Note that you can use the repo you cloned earlier as a basis for what each of the files should look like after the packages are linked.

Adding the tracking code

In the App.js file at the root of the project directory, import the react-native-analytics-segment-io package that you installed earlier. Optionally, you can extract AnalyticsConstants, this allows you to get the correct values for the package setup options as you’ll see later:

1import Analytics, {
2      AnalyticsConstants // optional
3    } from "react-native-analytics-segment-io";

Next, inside componentDidMount, initialize the package by supplying the write key you got earlier:

1componentDidMount() {
2      Analytics.setup("YOUR WRITE KEY")
3        .then(() => { // setup succeeded
4          this.initializeUser();
5        })
6        .catch((err) => { // setup failed
7          this.initializeUser();
8        });
9    }

In the code above, the setup function returns a promise, whether it succeeds or fails, we call the method which will initialize the user. I’ll explain what the initializeUser method does later. As for why we’re calling the same method whether it succeeds or fails, it’s because Analytics.setup only needs to be called once. This means that if you make changes to the code while developing, and then you reload the app, it will return an error if it’s called again. This is normal behavior, this allows us to call only the setup method once when the user launches the app. Calling the initializeUser method on failure allows us to do the same operation. That way, we can still proceed smoothly with the testing.

If you want to customize the default options, you can supply a second argument to the setup method. You usually don’t have to do this, except for special cases because these options are potentially invasive. Examples of these options include:

  • shouldUseBluetooth - whether the analytics client should record Bluetooth information.
  • shouldUseLocationServices - whether the analytics client should use location services.

You may want to supply the following options though:

  • flushAt - the number of events to batch before sending out the analytics data to the server. By default, this is set to 20. It’s a generous amount so if you want to change it to something lower, then you can. Just remember that the lower the number means the higher impact on battery as the app will have to perform the operation more often.
  • trackDeepLinks - whether to automatically track deep links.
  • trackApplicationLifecycleEvents - whether to automatically make a track call for application lifecycle events. This applies to things like when the app is installed, or the app is updated.

Here’s an example of how to set up with options supplied:

1Analytics.setup('YOUR WRITE KEY', {
2      [AnalyticsConstants.flushAt]: true,
3      [AnalyticsConstants.trackApplicationLifecycleEvents]: true
4    });

Here’s the initializeUser method. What it does is to identify the current user with their user ID. The current user’s email (email) and device information (device) are optional. In the code below, I’ve used a placeholder value for the email and user ID, you should replace those with the ones assigned by your app when the user signed up.

It’s also used to specify the screen in which the user is currently in. This gives some context on the events that we will be recording later on:

1initializeUser = () => {
2      let user_data = { 
3        email: "SOME EMAIL",
4        device: {
5          model: DeviceInfo.getModel(),
6          userAgent: DeviceInfo.getUserAgent()
7        },
8        timezone: DeviceInfo.getTimezone()
9      };
10    
11      Analytics.identify("SOME USER ID", user_data); // identify the user using the unique ID your app assigned to them
12      Analytics.screen("Home Screen");
13    }

In the sample App.js provided, we have the following tracking code, with an optional object containing the details of the action:

1viewAction = name => {
2      Analytics.track("View Pokemon", { pokemon: name });
3    };
4    
5    bookmarkAction = name => {
6      Analytics.track("Bookmark Pokemon", { pokemon: name });
7    };
8    
9    shareAction = name => {
10      Analytics.track("Share Pokemon", { pokemon: name });
11    };

If you want the user to have the ability to opt-out of the data collection, you can call the disable function based on their preferences:

    Analytics.disable();

Calling this function means all subsequent calls to track and screen methods will be ignored. Data collection can be switched back by calling the enable method:

    Analytics.enable();

To make sure that the SDK’s internal stores are cleared when a user logs out of the app, be sure to call the reset method. This is useful for cases where you’re expecting the user to be switching accounts often:

    Analytics.reset();

Running the app

At this point, you can now run the app on your Android or iOS device or emulator (Genymotion for Android or the iOS simulator for iOS):

1react-native run-android
2    react-native run-ios

Inspecting analytics data

If you haven’t done so already, click on the buttons on each card on the app to record some data. You can also change the email address if you want. But unless it’s a different emulator or device instance, Google Analytics will still consider it as the same user.

To view your analytics data, you can go to the Google Analytics website and view the real-time reports. Once you’re in that page, reload the app and you should see the active user and active screen:

Live analytics

You can also click on Events to view the events happening in real-time. Aside from that, there’s isn’t really much to see in the Google Analytics’ dashboard, unless you dig deeper into the audience demographics and other features which isn’t enabled by default.

Adding Keen IO

For us to view more details on the data we’ve gathered from the app, we can use Keen IO. This service allows us to dig deeper into the data that we’ve collected. It provides us with querying and visualization tools to gain more insight about the data.

The first step to add Keen IO is to sign up for an account. Once you have an account, it will ask you a few questions about how you plan to use their service.

Once that’s done, create a new project and navigate to the Access tab. This will show you the details that you’ll need to add to Segment.

Next, open the Segment website on a new browser tab, add a new destination and select Keen IO. Once selected, it will ask you which source you’d like to use. In this case, you can select the Android source we’ve added earlier:

Add Keen IO to Segment

Once Keen IO is added, it will ask you about the details of your Keen IO project. This is where you add the details you saw on the Access tab of your Keen IO project from earlier:

Keen IO destination settings

Once you’ve added the Project ID and Write Key, enable Keen IO by checking the toggle for the destination. At this point, you can now reload the app and do some actions. These actions will also now be recorded on Keen IO and ready for you to inspect.

If you go to the Explorer tab of your Keen IO project, you can view all the data which relates to an event by selecting extraction as the Analysis Type. The events recorded from the app can be selected in the Event Collection drop-down. Once you’ve selected an event, click on the Run Extraction button to execute the query. By default, this will format the data as table, but you can also select JSON from the drop-down on the upper right side of the screen:

Extraction Query

You can also set the Analysis Type to count and then group the data based on a specific field. In this case, I’ve selected pokemon. Unlike the extraction query, this allows you to present the data as a pie chart:

Count Group Query

I’ve only shown you a couple of queries, but there’s so much more you could do with Keen IO to learn more about your users.

Alternatives

In this section, we’re going to look at some of the alternative platforms to Segment, and other React Native libraries that you can use to implement analytics.

Alternatives to Segment

Segment is a great analytics tool, but if you want to explore your options, here are a few alternative platforms. All of these platforms integrate with a number of analytics and marketing tools just like Segment:

Alternative analytics libraries for React Native

Here are some React Native libraries that allows you to implement analytics:

Conclusion

That’s it! In this tutorial, you’ve learned how to add analytics to a React Native app using Segment. As you have seen, Segment is a valuable analytics tool that allows you to save engineering time through its integration with a number of analytics services and marketing tools.