React Native Tutorial: Facebook Login Example

by Didin J. on Oct 09, 2019 React Native Tutorial: Facebook Login Example

A comprehensive step by step React Native tutorial on implementing Facebook Login using React Native FBSDK including the working example

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. 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:

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.

React Native Tutorial: Facebook Login Example - FB Developer

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.

React Native Tutorial: Facebook Login Example - Create a New App ID

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

React Native Tutorial: Facebook Login Example - Facebook App Dashboard

Click the Facebook Login Set up button.

React Native Tutorial: Facebook Login Example - Setup iOS Android

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.

React Native Tutorial: Facebook Login Example - iOS Dev Environment

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

React Native Tutorial: Facebook Login Example - iOS Bundle Identifier

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

React Native Tutorial: Facebook Login Example - iOS Enable Single Sign On

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.

React Native Tutorial: Facebook Login Example - Android Download Facebook 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.

React Native Tutorial: Facebook Login Example - Android Package 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.

React Native Tutorial: Facebook Login Example - Android Key Hashes

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.

React Native Tutorial: Facebook Login Example - Android Enable Single Sign On

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.

React Native Tutorial: Facebook Login Example - Welcome React

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.

React Native Tutorial: Facebook Login Example - XCode configuration

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`.

React Native Tutorial: Facebook Login Example - React Native Android Structure

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 </dict> element.

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>fb{your-app-id}</string>
    </array>
  </dict>
</array>
<key>FacebookAppID</key>
<string>{your-app-id}</string>
<key>FacebookDisplayName</key>
<string>{your-app-name}</string>
<key>LSApplicationQueriesSchemes</key>
<array>
  <string>fbapi</string>
  <string>fb-messenger-share-api</string>
  <string>fbauth2</string>
  <string>fbshareextension</string>
</array>

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 <FBSDKCoreKit/FBSDKCoreKit.h>

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<UIApplicationOpenURLOptionsKey,id> *)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.

<string name="facebook_app_id">YOUR_FB_ID</string>

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

<uses-permission android:name="android.permission.INTERNET"/>

Add Facebook Application ID to the application element.

<application
   android:name=".MainApplication"
   ...>
   ...
   <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
 </application>


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 (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}>
          <Header />
          <View>
            <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 }}
                />
                <TouchableHighlight onPress={this.shareLinkWithDialog}>
                  <Text style={styles.shareText}>Share link with ShareDialog</Text>
                </TouchableHighlight>
              </Card>
            }
          </View>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};


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. You can watch the full demo of this React Native Facebook Login app.


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

That just the basic. If you need more deep learning about React.js, React Native or related you can take the following cheap course:

Thanks!

Loading…