Day 10: Integrating Analytics with Firebase in React Native


In this tutorial, you’ll learn how to set up Firebase Analytics in your React Native app. By the end of today’s lesson, you’ll be able to track custom events and view analytics data in the Firebase Console.


What You Will Learn Today:

  1. Setting up Firebase Analytics
  2. Tracking screen views and user events
  3. Logging custom events in Firebase
  4. Viewing analytics data in the Firebase Console

Step 1: Installing Firebase Analytics

To begin using Firebase Analytics, you’ll need to install the Firebase Analytics package for React Native.

  1. Install @react-native-firebase/analytics:
npm install @react-native-firebase/analytics
  1. For iOS, navigate to the ios directory and install the required CocoaPods:
cd ios
pod install
cd ..

Explanation:

  • @react-native-firebase/analytics: Provides Firebase Analytics functionality, enabling you to track events, user properties, and more.

Step 2: Configuring Firebase Analytics

Make sure your Firebase project is set up correctly. If you haven’t already, ensure that Firebase is configured in your app by following these steps:

  1. Place your google-services.json file in the android/app folder for Android.
  2. Place the GoogleService-Info.plist file in the ios project folder for iOS.

Enabling Analytics in Firebase Console

  1. Go to the Firebase Console, select your project, and go to Analytics.
  2. Make sure Analytics is enabled for your project.
See also  AI-powered Fake News Detection (Limited Scope with PHP)

Step 3: Tracking Screen Views Automatically

By default, Firebase Analytics can automatically track screen views if integrated with navigation libraries like React Navigation.

  1. Open App.js and configure React Navigation with Firebase Analytics:
import React, { useEffect } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import analytics from '@react-native-firebase/analytics';
import LoginScreen from './LoginScreen';
import HomeScreen from './HomeScreen';
import DetailsScreen from './DetailsScreen';

const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer
      onStateChange={async () => {
        const route = navigationRef.current?.getCurrentRoute();
        if (route) {
          await analytics().logScreenView({
            screen_name: route.name,
            screen_class: route.name,
          });
        }
      }}
    >
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
        <Stack.Screen name="Login" component={LoginScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Explanation:

  • logScreenView: Logs screen views in Firebase Analytics, providing data on how users navigate within your app.
  • onStateChange: Listens to navigation changes and triggers logScreenView whenever the user switches screens.

Step 4: Logging Custom Events

Firebase Analytics supports custom events, which are useful for tracking specific user actions like button presses, form submissions, or in-app purchases.

  1. Open a component, such as HomeScreen.js, and add custom event tracking:
import React from 'react';
import { View, Text, Button } from 'react-native';
import analytics from '@react-native-firebase/analytics';

export default function HomeScreen() {
  const logCustomEvent = async () => {
    await analytics().logEvent('button_click', {
      screen: 'Home',
      purpose: 'Navigate to details',
    });
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => {
          logCustomEvent(); // Log custom event when button is pressed
          navigation.navigate('Details');
        }}
      />
    </View>
  );
}

Explanation:

  • logEvent: Logs custom events in Firebase Analytics, allowing you to track user actions with specific event names and properties.
  • button_click: The name of the custom event. You can track multiple events with unique names (e.g., purchase, sign_up).
See also  Day 5: Implementing Middleware and Error Handling

Step 5: Tracking User Properties

User properties help you group users by specific characteristics (e.g., subscription type, app version) for more detailed analytics.

  1. In App.js or a similar entry point, set user properties when the app starts:
import analytics from '@react-native-firebase/analytics';

const setUserProperties = async () => {
  await analytics().setUserProperty('subscription_plan', 'premium');
};

function App() {
  useEffect(() => {
    setUserProperties(); // Set user properties when the app starts
  }, []);

  // Rest of your code
}

Explanation:

  • setUserProperty: Assigns a custom user property in Firebase Analytics.
  • subscription_plan: A user property to identify users with different subscription plans (e.g., premium, basic).

Step 6: Viewing Analytics Data in the Firebase Console

After setting up Firebase Analytics in your app, you can view data directly in the Firebase Console.

  1. Go to the Firebase Console and select your project.
  2. Navigate to Analytics > Dashboard.
  3. Here, you can view user engagement metrics, including active users, demographics, and custom events.
  4. In Events, you can see all custom events (like button_click) and view how frequently users are performing each action.

Explanation:

  • Firebase Console Dashboard: Provides insights into user behavior, event frequency, and screen views.
  • Events Section: Displays all custom events, allowing you to track the most common user actions within your app.

Step 7: Recap and Summary

In today’s tutorial, you learned how to integrate Firebase Analytics into a React Native app to track user interactions and engagement. Here’s a quick summary of what you’ve done:

  • Installed Firebase Analytics to track user interactions in your app.
  • Configured React Navigation to automatically track screen views.
  • Logged custom events to track specific user actions.
  • Set user properties to segment and analyze users based on attributes.
  • Viewed analytics data in the Firebase Console to monitor app usage.
See also  Integrating Billplz with PHP Laravel

With Firebase Analytics integrated, you can now make data-driven decisions to improve user engagement, retention, and app performance.


Conclusion

This concludes our 10-day series on Advanced React Native Features! Over the past 10 days, you’ve learned a variety of advanced techniques, from setting up navigation and managing state to implementing in-app purchases and tracking analytics. You now have a solid foundation to build complex, high-quality React Native applications with modern features.

Congratulations on completing the series! Let me know if you need further guidance or clarification on any of these topics. Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

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