How to Add Firebase Crashlytics in React Native App

React Native Firebase Crashlytics

This is our fifth post of React Native Firebase series, in this example we will see what is Firebase Crashlytics? and how to integrate Crashlytics in React Native App? How to see Crash Reports in Firebase Console? So Let’s start with the Firebase Crashlytics Example.

Firebase Crashlytics

Firebase Crashlytics is a word made of Crash + Analytics which means it helps you to collect analytics and details about crashes and errors that occur in your app. It does this through three aspects:

  • Logs: Log events in your app to be sent with the crash report for context if your app crashes.
  • Crash reports: Every crash is automatically turned into a crash report and sent.
  • Stack traces: Even when an error is caught and your app recovers, the JavaScript stack trace can still be sent.

To learn more, view the Firebase Crashlytics documentation.

Use of Firebase Crashlytics

As mentioned above, Crashlytics help you to collect analytics and details about crashes and errors. There are various methods to set attributes for the crash report using Crashlytics, in order to provide analytics for crashes and help you review them. Set methods help us to set predefined attributes, but we can also set our own custom attributes.

crashlytics().setUserId(user.uid),
crashlytics().setAttribute('credits', String(user.credits)),
crashlytics().setAttributes({
  role: 'admin',
  followers: '13',
  email: user.email,
  username: user.username
}),

We can use log method throughout our app to accumulate extra context for possible crashes that can happen.

crashlytics().log('App mounted.');

To test Crashlytics we can use crash method to crash the app forcefully

crashlytics().crash()

Crashlytics also supports sending JavaScript stack traces to the Firebase console. This can be used in any situation where an error occurs but is caught by your own code to recover gracefully. To send a stack trace, pass a JavaScript Error to the recordError method.

crashlytics().log('Updating user count.');
try {
  if (users) {
    // An empty array is truthy, but not actually true.
    // Therefore the array was never initialised.
    setUserCounts(userCounts.push(users.length));
  }
} catch (error) {
  crashlytics().recordError(error);
  console.log(error);
}

If you want to stop collecting any Crashlytics anytime then you can use setCrashlyticsCollectionEnabled to disable the crashlytics collection.

crashlytics().setCrashlyticsCollectionEnabled(false)

Example Description

In this example we will integrate Firebase Crashlytics and going to log the Crash in Firebase console. We will create a simple screen to log user details, crashes and error on click of different buttons. We will also add some additional log when app launches to see if we can see them in console or not. So let’s see how the code for this looks like.

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 init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

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

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

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 crashlytics module

npm install @react-native-firebase/crashlytics --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 ..

Additional Setup for Android

We have to add somethings to integrate Crashlytics for Android. Which you can find here.

Code to Integrate Crashlytics in React Native

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

App.js

// #5 How to Add Firebase Crashlytics in React Native App
// https://aboutreact.com/react-native-firebase-crashlytics/

// Import React in our code
import React, { useEffect, useState } from "react";

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

import crashlytics from "@react-native-firebase/crashlytics";

const App = () => {
  const [userCounts, setUserCounts] = useState(null);

  useEffect(() => {
    crashlytics().log("App mounted.");
  }, []);

  const logCrashlytics = async () => {
    crashlytics().log("Dummy Details Added");
    await Promise.all([
      crashlytics().setUserId("101"),
      crashlytics().setAttribute("credits", String(50)),
      crashlytics().setAttributes({
        email: "aboutreact11@gmail.com",
        username: "aboutreact11",
      }),
    ]);
  };

  const logCrash = async (user) => {
    crashlytics().crash();
  };

  const logError = async (user) => {
    crashlytics().log("Updating user count.");
    try {
      if (users) {
        // An empty array is truthy, but not actually true.
        // Therefore the array was never initialised.
        setUserCounts(userCounts.push(users.length));
      }
    } catch (error) {
      crashlytics().recordError(error);
      console.log(error);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.titleText}>
        How to Add Firebase Crashlytics in React Native App
      </Text>
      <View style={styles.innerContainer}>
        <TouchableOpacity
          activeOpacity={0.5}
          style={styles.buttonStyle}
          onPress={() => logCrashlytics()}
        >
          <Text style={styles.buttonTextStyle}>
            Log User Details
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          activeOpacity={0.5}
          style={styles.buttonStyle}
          onPress={logCrash}
        >
          <Text style={styles.buttonTextStyle}>
            Log Crash
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          activeOpacity={0.5}
          style={styles.buttonStyle}
          onPress={logError}
        >
          <Text style={styles.buttonTextStyle}>
            Log Error
          </Text>
        </TouchableOpacity>
      </View>
      <Text style={styles.footerHeading}>
        React Native Firebase Crashlytics
      </Text>
      <Text style={styles.footerText}>
        www.aboutreact.com
      </Text>
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  innerContainer: {
    flex: 1,
    alignItems: "center",
    padding: 35,
    justifyContent: "center",
  },
  titleText: {
    fontSize: 30,
    fontWeight: "bold",
    textAlign: "center",
    paddingVertical: 20,
  },
  buttonTextStyle: {
    color: "white",
    fontWeight: "bold",
  },
  buttonStyle: {
    alignItems: "center",
    backgroundColor: "orange",
    padding: 10,
    width: "100%",
    marginTop: 16,
  },
  footerHeading: {
    fontSize: 18,
    textAlign: "center",
    color: "grey",
  },
  footerText: {
    fontSize: 16,
    textAlign: "center",
    color: "grey",
  },
});

Crashlytics Setup

After doing all this setup and replacing the code we have to enable the crashlytics from Firebase Console and to do that open your Firebase Console and click on the Crashlytics tab

react_native_crashlytics_setup1

Once you are there, you can click on “Enable Crashlytics”

react_native_crashlytics_setup2

After enabling it you will see it waits for your app to connect for the first time. Now you have to launch your app.

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

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

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

If your app launched successfully with proper setup then you can see “Installation Successful!” message and go to dashboard option. All this things will be required for the Android and iOS both.

react_native_crashlytics_setup3

Output Screenshots

react_native_crashlytics1

FYI: Crashlytics reports will be visible after a day on the Firebase dashboard

react_native_crashlytics2

react_native_crashlytics3

react_native_crashlytics4

Download Source Code

This is how to add Firebase Crashlytics in React Native App for Android and iOS. 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 “How to Add Firebase Crashlytics in React Native App”

  1. How can we find exact line number of file the bug is occurred with index.bundle.[line_number], then integrating it is useless, if we can’t find the exact file & its line number.

    Reply

Leave a Comment

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