Add Firebase Analytics in React Native App | React Native Firebase

React Native Firebase Analytics

Hey Guys, Finally we are here with a complete series to integrate Firebase features/functionality in React Native App for Android and iOS both. I am sure all of you heard about Firebase, if not then you should know about it as it is a complete suite to create successful apps. It helps you to accelerate and scale app development without managing infrastructure so with Firebase you can focus on app development instead of managing infrastructure. In this series we will explore the Firebase Analytics, databases, authentication, In-App messaging, push notifications, AdMob and many more things. So let’s get started with the first example to add Firebase analytics in React Native App.

In this complete series we are going to use React Native Firebase which is a very simple to integrate library and provides lots of functionalities. React Native Firebase is the officially recommended collection of packages that brings React Native support for all Firebase services on both Android and iOS apps.

Firebase Analytics

Google Analytics for Firebase collects usage and behaviour data for your app. Firebase Analytics provides free, unlimited reporting on up to 500 distinct events. Its two primary concerns are:

  1. Events: What is happening in your app, such as user actions, system events, or errors
  2. User properties: Attributes you define to describe segments of your user base, such as language preference or geographic location

The SDK automatically captures certain key events and user properties. Once you integrate Firebase analytics with your app, it starts logging some events (ad_click, app_clear_data, app_remove, app_update etc) and user properties (Age, App Version, Country, Device details etc) without writing a single line of code. You can also define your own custom events to measure the things that uniquely matter to your business. Analytics offers so many different predefined events to track user behaviour.

Custom, Predefined and Reserved Events

There are so many tool in the market which can provide the analytics for your app but the beauty of Google Analytics is its smart event capturing capability. There are so many Reserved event which analytics captures automatically and also provide you the facility to capture any custom event you want.

You can capture any custom event very easily using logEvent function in which you just have to pass the event name and the payload you want to capture on that event. Please try to avoid using Reserved events, it will throw an error in case you use any event name similar to reserves events name.

analytics().logEvent('my_custom_event', {
  id: 101,
  item: 'My Product Name',
  description: ['My Product Desc 1', 'My Product Desc 2'],
});

If we talk about the predefined events then Firebase provides many Predefined event methods which will help you to capture the event from different type of apps like e-commerce, travel, and gaming apps. You can use any predefined event easily like

analytics().logAddPaymentInfo({
  coupon: 'OfferZero',
  currency: 'INR',
  items: ['T-Shirt'],
  payment_type: 'Credit Card',
  value: 1000,
});

Screen Tracking

In the field of analytics, screen tracking plays a major role as it shows interest of your app users in different features. For example if you have 10 different features in your app and each one served in different screen then on the basis of screen tracking you can easily find which feature is most popular and which one needs some updates.

We all know React Native applications run inside a single Activity/ViewController, meaning any screen changes won’t be tracked by the native Firebase SDKs. There are a number of ways to implement navigation within React Native apps, therefore there is no “one fits all” solution to screen tracking. But e have some predefined events which can help us to do that like logScreenView.

With the help of logScreenView event you can easily capture the movement of screen

await analytics().logScreenView({
  screen_name: currentRouteName,
  screen_class: currentRouteName,
});

You can see the usage of the same while using React Navigation and React Native Navigation.

I think that is enough, now we can move to the code and can see how to integrate Firebase/Google analytics in React Native App.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.

If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:

npm uninstall -g react-native-cli @react-native-community/cli

Run the following commands to create a new React Native project

npx react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

npx react-native init ProjectName --version X.XX.X

Note If the above command is failing, you may have old version of react-native or react-native-cli installed globally on your pc. Try uninstalling the cli and run the cli using npx.

This will make a project structure with an index file named App.js in your project directory.

Integration of Firebase SDK

For starting with any of the React Native Firebase Example you will need to integrate Firebase in your app, I have specially made a separate post in detail for this where you will see point to point process to add Firebase in your React Native App for Android and iOS both.

Please visit How to Integrate Firebase in Android and iOS App and come back for the next step.

Once you are done with the Firebase integration you can install the further dependencies.

Installation of Dependencies

To install the dependencies open the terminal and jump into your project using

cd ProjectName

For the React Native Firebase we need to install and setup the app module

npm install @react-native-firebase/app --save

Now install the analytics module

npm install @react-native-firebase/analytics --save

This command will copy all the dependencies into your node_module directory. –save is optional, it is just to update the dependency in your package.json file.

CocoaPods Installation

After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but for iOS we need to install the pods. So to install the pods use

cd ios/ && pod install --repo-update && cd ..

Code to Integrate Firebase Analytics

Please open App.js in any code editor and replace the code with the following code

App.js

// React Native Firebase
// #1 Add Firebase Analytics in React Native App
//https://aboutreact.com/react-native-firebase-analytics

// Import React in our code
import React from 'react';

// Import all the components we are going to use
import {
  SafeAreaView,
  TouchableOpacity,
  StyleSheet,
  View,
  Text,
} from 'react-native';

// Import Firebase Analytics
import analytics from '@react-native-firebase/analytics';

const App = () => {
  const realtimeLogContent = () => {
    analytics().logSelectContent({
      content_type: 'Button Clicked',
      item_id: 'button1',
    });
  };

  const logCustomeEvent = () => {
    analytics().logEvent('my_custom_event', {
      id: 101,
      item: 'My Product Name',
      description: ['My Product Desc 1', 'My Product Desc 2'],
    });
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.container}>
        <Text style={styles.heading}>
          React Native Firebase
        </Text>
        <Text style={styles.normalTextStyle}>
          #1 Firebase Analytics
        </Text>
        <View style={styles.innerContainer}>
          <Text style={styles.normalTextStyle}>
            Log React Time Content
          </Text>
          <TouchableOpacity
            activeOpacity={0.7}
            style={styles.buttonStyle}
            onPress={realtimeLogContent}>
            <Text style={styles.buttonTextStyle}>
              Click Button
            </Text>
          </TouchableOpacity>
          <Text style={styles.normalTextStyle}>
            Trigger My Custom Event
          </Text>
          <TouchableOpacity
            activeOpacity={0.7}
            style={styles.buttonStyle}
            onPress={logCustomeEvent}>
            <Text style={styles.buttonTextStyle}>
              Create Custom Event
            </Text>
          </TouchableOpacity>
        </View>
      </View>
      <Text
        style={{
          fontSize: 16,
          textAlign: 'center',
          color: 'grey',
        }}>
        www.aboutreact.com
      </Text>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    padding: 10,
    alignItems: 'center',
  },
  innerContainer: {
    flex: 1,
    alignItems: 'center',
  },
  heading: {
    fontSize: 30,
  },
  buttonStyle: {
    minWidth: 300,
    justifyContent: 'center',
    padding: 10,
    backgroundColor: '#8ad24e',
  },
  buttonTextStyle: {
    color: 'white',
    textAlign: 'center',
  },
  normalTextStyle: {
    color: 'black',
    textAlign: 'center',
    marginVertical: 20,
    fontSize: 18,
  },
});

export default App;

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

1. Start Metro Bundler

First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:

npx react-native start

Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.

2. Start React Native Application

To run the project on an Android Virtual Device or on real debugging device:

npx react-native run-android

or on the iOS Simulator by running (macOS only)

npx react-native run-ios

Output Screenshots

react_native_firebase_analytics
google_analytics_dashboard1
google_analytics_dashboard2

That was how you can Integrate Firebase Analytics in your React Native App for Android and iOS. If you want to disable auto initialization of Firebase you can see this. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

1 thought on “Add Firebase Analytics in React Native App | React Native Firebase”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.