DEV Community

kris
kris

Posted on • Originally published at heartbeat.fritz.ai on

Implementing Facebook login on Android with React Native and Firebase

Image Source

This tutorial is a quick guide on how to integrate Facebook login with Firebase while developing with React Native. By using Firebase and Facebook login, you’ll be able to understand how to use and integrate Firebase properly, as well as implement Facebook authentication along with login. This process will also help developers learn a lot about Firebase, which can be used as lightweight and easy-to-configure backend.

Nowadays, Facebook login has become important in a wide range of apps, as it will provide users with an easier login approach than having to manually enter credentials. It’s a simple but effective way to improve an app’s UX.

First, you’ll learn about the integration of React Native Firebase starter boilerplate using the GitHub repository.

react-native-firebase-starter is a bare-bones react native app with react-native-firebase pre-integrated so you can get started quickly.

Then, you’ll integrate react-native-fbsdk into your React Native project to enable the Facebook login. This plugin is a React Native wrapper around the Facebook SDKs for Android and iOS, which provides access to Facebook login, sharing, graph requests, app events, etc. All the configurations required are explained in detail below. At the end of this tutorial, you’ll be able to create your own React Native Firebase project that includes a Facebook login.

Setting up Firebase Boilerplate

To quickly and easily set up the for our project, we’ll clone a react-native-firebase-starter package. It’s a boilerplate for your project that will have all the configuration required for the Firebase setup. We do this by simply cloning the GitHub repo into our local drive. The command to clone the repo is given below:

git init
git clone https://github.com/invertase/react-native-firebase-starter

As a result, you’ll see a React Native project folder in your drive with all the needed configurations. Now we need to install those configurations.

To do that we run yarn, which will install all the required plugins and packages required for the React Native Firebase project. This finalizes our setup of the starter project and we’ll see google-service.json in our project files, generated from the Firebase console.

After app creation is complete, we need to select the Android app and open MainApplication.java in our IDE. There we’ll see an imported package named com.invertase.rnfirebasestarted_._ We need to copy com.invertase.rnfirebasestarter and paste it into the Firebase console, as shown in the screenshot below:

Follow the guiding points in the screenshots and download the google-services.json file into our project folder:

After downloading the google-services.json file into your project folder, we need to move the file from the main project folder into the project’s app folder.

Then, we start the app / project using the command below:

react-native run-android

Then, we’ll see the following result in our Android emulator:

Finally, we can see that our Firebase integration is working properly. Now we can move on to adding Facebook login into our app.

The next revolution in mobile development? Machine learning. Don’t miss out on the latest from this emerging intersection. Sign up for weekly updates from our crew of mobile devs and machine learners.

Setting up the Facebook SDK plugin

Since we’ve integrated the Firebase plugin using the official documentation. To integrate the Facebook login, the docs recommend that developers usethe react-native-fbsdk package. So let’s get started by installing the plugin as follows:

Using yarn:

yarn add react-native-fbsdk

Or, using NPM (Node Package Manager):

npm install react-native-fbsdk

After installing the Facebook SDK package, we must link the SDK to configure the iOS and Android projects. We can do that by using the following piece of code in our project console:

react-native link react-native-fbsdk

Now, go to MainApplication.java and MainActivity.java under app/src/main/java/com// to complete the setup.

In MainApplication.java, we need to add an instance variable of type CallbackManager and its getter. You can use the code snippet below to do that:

import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.facebook.appevents.AppEventsLogger;
...

public class MainApplication extends Application implements ReactApplication {

  private static CallbackManager mCallbackManager = CallbackManager.Factory.create();

  protected static CallbackManager getCallbackManager() {
    return mCallbackManager;
  }
    //...

The example of the above code used in the app project is shown below:

Now, we’ll need to register the SDK package using the getPackages() method. Follow the code snippet below to do that:

private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new FBSDKPackage(mCallbackManager)
      );
    }
};

The integration of the above code in the app project is shown by the screenshot below:

Now, in the MainActivity.java file, we need to override the method onActivityResult():

import android.content.Intent;

public class MainActivity extends ReactActivity {

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data);
    }
    //...

And again, the above code in our project environment:

After this is done, test the result in the IDE Android mobile emulator by running our app. The result can be seen in the screenshot below:

The above screenshot shows the occurrence of the error. This error is due to not establishing the APP_ID. You can find the solution of this error here.

Now, open the android/app/src/main/AndroidManifest.xml file and look for the tag to confirm that this meta-data tag exists:

<meta-data android:name="com.facebook.sdk.ApplicationId"
          android:value="@string/facebook\_app\_id"/>

Then, we open the android/app/src/main/res/values/strings.xml file and confirm that there’s a facebook_app_id string tag with our app id as the value:

<string name="facebook\_app\_id">YOUR\_APP\_ID\_HERE</string>

Finally, we run react-native run-android again to get the following result in our IDE android emulator:

Finally, our configuration of react-native-fbsdk is completed.

But we need to remember that to activate Facebook login on the Firebase console, we have to add a copy of the APP_ID and APP_SECRET from our facebook developer account.

Coding phase for setting up Facebook login

Here, we follow the guide provided by rnfirebase.io on setting up social authentication required during Facebook login. Here, we’ll try to prove that the normal flow given in the guide works.

In App.js, import the AccessToken and LoginManager modules from react-native-fbsdk package:

import { AccessToken, LoginManager } from "react-native-fbsdk";

After that, we need to create a function to handle the Facebook login logic. Here, we’ve created an asynchronous function called facebookLogin() to handle all the logic of logging in, permissions, authentication, and error throwing (if it occurs). You can see the logic in the code snippet below:

Now, we need to provide users a button for the Facebook login, which when triggered, runs the above function to login with Facebook. We do that by using the following piece of code:

<Button title="Login with Facebook" onPress={this.facebookLogin} />

Let’s try it out

Save the code and then reload the IDE android emulator. You’ll see the following result:

Here, when we click on the button, it triggers a web-view because we haven’t yet installed a native app on an emulator.

For quick testing, you can create a test user from your Facebook developer account, as shown in the screenshot below:

Finally, click on the login button, and you’ll be directed to the Facebook authentication page, as shown in the screenshot below:

Accept it and click “Continue” to complete the login with Facebook.

Now, to see the login result, we need to open debug mode on your browser and check the console as follows:

Upon the success of the above step, we’ve completed the integration of the Facebook plugin in our React Native Firebase app.

Summary

This tutorial has shown you how to quickly setup Firebase on React Native, and then set up the Facebook SDK to integrate Facebook login into your app. You also should leave knowing different configurations based on Firebase guides and also have learned how to fix some common issues with these configurations.

By completing this tutorial, you should be able to test your app and create your very own version of a React Native Firebase app with a Facebook login feature. We’ll continue with a look at integrating this on iOS in the next tutorial.

Looking for new ways to elevate your mobile app’s user experience? With Fritz, you can teach your apps to see, hear, sense, and think. Learn how and start building with a free account.

Editor’s Note:Join Heartbeat on Slack and follow us onTwitter andLinkedIn for the all the latest content, news, and more in machine learning, mobile development, and where the two intersect.


Top comments (0)