React Native Tutorial: Facebook login using React Native FBSDK

React Native Tutorial: Facebook login using React Native FBSDK

In this React Native tutorial, we will show you how to implementing or integrating Facebook login using React Native FBSDK (react-native-fbsdk) library/module. React Native FBSDK is a wrapper around the iOS Facebook SDK and Android Facebook SDK, allowing for Facebook integration in React Native apps

A comprehensive step by step React Native tutorial on implementing Facebook Login using React Native FBSDK including the working example.
Every access to the Native components is provided by Javascript modules. We have focused on the FB login that is the standard of almost all authenticated Mobile apps.

Table of Contents:

  • Setup a Facebook App
  • Install React Native CLI and Create App
  • Install React Native FBSDK (react-native-fbsdk) Module
  • Implements Facebook Login, Logout, and Share
  • Run and Test React Native Facebook Login App

The flow of this React Native FB login is very simple. Just a page with a "Sign in with Facebook" button which after clicking the FB login and successful login it will return with the basic info of your Facebook account. The following tools, frameworks, and modules are required for this tutorial:

  1. React Native
  2. Node.js (NPM or Yarn)
  3. react-native-fbsdk module
  4. React Native Elements
  5. Facebook Developer Dashboard
  6. Android Studio or SDK for Android
  7. XCode for iOS
  8. Terminal (OSX/Linux) or Command Line (Windows)
  9. Text Editor or IDE (We are using VSCode)

Before start to the main steps, make sure that you have installed Node.js and can run npm in the terminal or command line. To check the existing or installed Node.js environment open the terminal/command line then type this command.

node -v
v10.15.1
npm -v
6.11.2
yarn -v
1.10.1
Setup a Facebook App

This step is about to set up or create a Facebook App to get the App ID and secret. Also, set the bundle ID for native iOS and Google Play package names for native Android. To set up or create a Facebook App, go to the Facebook Developers Dashboard. Login with your Facebook developers' account or credentials.

Click the + Add a New App button. Enter the display name (we use MyIonicApp name) then click the Create App ID button. Make sure to use the valid name allowed by Facebook Developers.

After checking the captcha dialog and click submit button, now, you can see App ID and Secret, write it to your notepad.

Click the Facebook Login Set up button.

Choose iOS first then on the iOS wizard scroll down to the bottom to enter iOS bundle ID that will supply on the XCode later.

Select SDK: Cocoapods as a development environment before using Facebook Login for iOS then click the Next button.

Enter iOS bundle ID that will supply on config.xml later (we use "com.djamware.myreactnativeapp") then click save then click the Continue button.

Enabled the Single Sign-On feature then click Save and Next button a few times until the end of the iOS steps. Next, click on the Android tab then click Download Android SDK.

Click the Next button 2 times then fill the Android project package name (we use "com.djamware.myreactnativeapp") and default Android Activity Class name.

Click the save button and this setup will check to the Google Play for the existence of this package name. You can ignore the popup message if there's no package found in the Google Play. Click the Continue button.

As you see, we need to create a Key Hashes. To get the key hashes, especially in development build open the terminal or command line then type this command.

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

Enter "android" as the Key Pass.

Enter keystore password:  android
K1IC8IKUNGj8tt2BHTpm11c7uRE=

Copy and paste the Key Hashes like above to the Key Hashes field of the Facebook Android Setup then click save and continue button.

Enabled Single Sign-On then click Next button a few times until the end of the Facebook Android setup.

Install React Native CLI and Create App

This time we will use React Native CLI to create a React Native app because the Firebase Cloud Messaging will use natively. To install it, type this command in your App projects folder.

sudo npm install -g react-native-cli

Then create a React Native App using this command from your project directory.

react-native init ReactNativeFacebook

Next, go to the newly created React App folder and run the React Native app to the simulator.

cd ReactNativeFacebook && react-native run-ios

When a new terminal window opened, go to the React Native project folder then run the Metro bundler server.

cd ~/Apps/ReactNativeFacebook && yarn start

Now, you will see this in the iOS simulator.

Next, we will change the iOS and Android package name or bundle ID to match the Firebase configuration files. For iOS, open the ios/ReactNativeFacebook.xcworkspace file using XCode.

Just change the Bundle Identifier (ours: com.djamware.myreactnativeapp) and it ready to use with the Facebook App. For Android a little tricky, first, change the source folders which previously android/app/src/main/java/com/reactnativefacebook become android/app/src/main/java/com/djamware/myreactnativeapp.

Next, open and edit android/app/src/main/java/com/djamware/myreactnativeapp/MainActivity.java then this package name.

package com.reactnativefacebook;

to

package com.djamware.myreactnativeapp;

Do the same way to android/app/src/main/java/com/djamware/myreactnativeapp/MainApplication.java. Next, open and edit android/app/src/main/AndroidManifest.xml then change this line.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.reactnativefacebook">

To

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.djamware.myreactnativeapp">

Next, open edit android/app/build.gradle then change the application ID to the new package.

android {
    ...
    defaultConfig {
        applicationId "com.djamware.myreactnativeapp"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    ...
}

Next, open and edit android/app/BUCK then change the android_build_config and android_resource package name.

android_build_config(
    name = "build_config",
    package = "com.djamware.myreactnativeapp",
)

android_resource(
    name = "res",
    package = "com.djamware.myreactnativeapp",
    res = "src/main/res",
)

Finally, run this command from the android folder to clean up the Gradle.

cd android
./gradlew clean
Install React Native FBSDK (react-native-fbsdk) Module

To install React Native FBSDK (react-native-fbsdk) module, type this command.

yarn add react-native-fbsdk

or

npm install --save react-native-fbsdk

Next, you need to link this module to the Native iOS and Android using this command.

react-native link react-native-fbsdk

Configure Facebook SDK iOS

To configure the Facebook SDK for iOS, go to the iOS folder then install Cocoapods.

cd ios
pod install

Next, open the ReactNativeFacebook.xcworkspace file using XCode then right-click the Info.plist and select Open As -> Source Code. Add these lines of XML snippets before the closing of element.

CFBundleURLTypes

  
    CFBundleURLSchemes
    
      fb{your-app-id}
    
  

FacebookAppID
{your-app-id}
FacebookDisplayName
{your-app-name}
LSApplicationQueriesSchemes

  fbapi
  fb-messenger-share-api
  fbauth2
  fbshareextension

Change {your-app-id} and {your-app-name} with the Facebook App ID and Name that showed up in the Facebook Developer App Dashboard that previously created. Next, we have to manually add a few Obj-C codes to make Facebook App integration works. Open and edit AppDelegate.m the file then add this import.

#import 

Add FBSDKApplicationDelegate before the return line.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"ReactNativeFacebook"
                                            initialProperties:nil];

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];

  [[FBSDKApplicationDelegate sharedInstance] application:application
                           didFinishLaunchingWithOptions:launchOptions];

  return YES;
}

Also, add this method below didFinishLaunchingWithOptions method.

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary *)options {

  BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
                                                                openURL:url
                                                      sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
                                                             annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
                  ];
  // Add any custom logic here.
  return handled;
}

To send the Facebook App event to the Facebook App Dashboard analytics add this method.

- (void)applicationDidBecomeActive:(UIApplication *)application {
  [FBSDKAppEvents activateApp];
}

Configure Facebook SDK Android

To configure Facebook SDK for Android, open and edit the main or root Build.gradle then add this mavenCentral() repository to buildscript { repositories {}}.

repositories {
    google()
    jcenter()
    mavenCentral()
}

Next, open and edit android/app/build.gradle then add this dependency inside dependencies {} body.

implementation 'com.facebook.android:facebook-android-sdk:[5,6)'

Next, build this Android app to make the Facebook SDK library installed by type this command inside the android folder.

./gradlew build

Next, to add Facebook App ID to Android app, open and edit android/app/res/values/strings.xml then add this value.

YOUR_FB_ID

Replace YOUR_FB_ID with your Facebook App ID. Next, open and edit android/app/manifests/AndroidManifest.xml then make sure this permission added.


Add Facebook Application ID to the application element.

<application
   android:name=".MainApplication"
   ...>
   ...
   
 
Implements Facebook Login, Logout, and Share

Now, we will implement a Facebook login, logout, and share. First, we need to add React Native Elements to use the nice component for the React Native app. Type this command to install it.

yarn add react-native-elements
yarn add react-native-vector-icons

or

npm i react-native-elements --save
npm i --save react-native-vector-icons

Then link the react-native-vector-icons with the Native iOS and Android app.

react-native link react-native-vector-icons

Next, to implement Facebook login, logout, and share, we will use just a single existing App.js. Open and edit that file then add or modify these imports of React Hooks useState, useEffect, required React Native components, required React Native FBSDK components, and required React Native Elements components.

import React, { useState, useEffect } from 'react';
import {
  Alert,
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  StatusBar,
  Text,
  TouchableHighlight
} from 'react-native';

import {
  Header,
  Colors,
} from 'react-native/Libraries/NewAppScreen';
import { LoginButton, AccessToken, ShareDialog, GraphRequest, GraphRequestManager } from 'react-native-fbsdk';
import { Card, Image } from 'react-native-elements'

Change the generated App constant to this declaration.

const App = () => {
...
}

Declare the required variable using React Hooks useState in the top of App constant body.

const [profile, setProfile] = useState([]);
const [profileImage, setProfileImage] = useState();
const [isLoggedIn, setLoggedIn] = useState(false);

Declare a constant variable as the content for Facebook shares.

const SHARE_LINK_CONTENT = {
  contentType: 'link',
  contentUrl: 'https://www.facebook.com/',
};

Add a function to get Facebook public_profile that put the response to profile and profileImage variables using setProfile and setProfileImage useState.

getPublicProfile = async () => {
  const infoRequest = new GraphRequest(
    '/me?fields=id,name,picture',
    null,
    (error, result) => {
      if (error) {
        console.log('Error fetching data: ' + error.toString());
      } else {
        console.log(result);
        setProfile(result);
        setProfileImage(result.picture.data.url);
      }
    }
  );
  new GraphRequestManager().addRequest(infoRequest).start();
}

Add a function or method to share the link with dialog opened and using the content from the previously declared constant variable.

shareLinkWithDialog = async () => {
  const canShow = await ShareDialog.canShow(SHARE_LINK_CONTENT);
  if (canShow) {
    try {
      const {isCancelled, postId} = await ShareDialog.show(
        SHARE_LINK_CONTENT,
      );
      if (isCancelled) {
        Alert.alert('Share cancelled');
      } else {
        Alert.alert('Share success with postId: ' + postId);
      }
    } catch (error) {
      Alert.alert('Share fail with error: ' + error);
    }
  }
};

Modify the View to implement the UI of Facebook Login, Profile, Share, and Logout.

return (
    
      
      
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}>
          
          
            <LoginButton
              onLoginFinished={
                (error, result) => {
                  if (error) {
                    console.log("login has error: " + result.error);
                  } else if (result.isCancelled) {
                    console.log("login is cancelled.");
                  } else {
                    setLoggedIn(true);
                    AccessToken.getCurrentAccessToken().then(
                      (data) => {
                        console.log(data.accessToken.toString());
                        this.getPublicProfile();
                      }
                    )
                  }
                }
              }
              onLogoutFinished={() => {
                console.log("logout.");
                setLoggedIn(false);
              }}/>
            { isLoggedIn && <Card
                title={profile.name}>
                <Image
                  source={{ uri: profileImage }}
                  style={{ width: 50, height: 50 }}
                />
                
                  Share link with ShareDialog
                
              
            }
          
        
      
    
  );
};
Run and Test React Native Facebook Login App

To run the whole React Native Facebook Login App, first, re-link again the React Native to React Native FBSDK.

react-native unlink react-native-fbsdk
react-native link react-native-fbsdk

Run the React Native app to the Android device using this command. Make sure the Android device connected using USB cable and USB Debugging is enabled so it can be detected using ADB command.

react-native run-android

The new terminal tab will open then run the Metro Bundler after going to the root of the project folder.

cd ~/Apps/ReactNativeFacebook && yarn start

For the iOS, we can open the ios/ReactNativeFacebook.xcworkspace from the XCode then use the valid provisioning profile signing then run the iOS app from there while the Metro Bundler runs from the terminal.

That it's, the React Native Facebook login app. You can find the full source from our GitHub.

ECommerce Mobile App Development | Ecommerce Mobile App Development Services

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates. **Know about [Top ECommerce Mobile App Development...

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates.

Know about Top ECommerce Mobile App Development Company

React Native Vs Native : Which Is The Best For Your Mobile App?

Hence, Native app development needs more time, money, & resources to build an app.


In this article, we are going to find out which is better between React native vs native.

Does the Instagram app use React Native from Facebook?

If you want to build mobile applications and want to learn cross-platform applications development, then React Native is an excellent concept to learn about something new. Today, Facebook, Instagram, Airbnb, Tesla, Skype, and Walmart all use React Native to build and maintain their mobile apps.