Adding social login to your mobile app improves user experience by simplifying the authentication process. In this tutorial, you'll learn how to integrate Facebook Login into a React Native app using the latest Facebook SDK and best practices for Android and iOS.
We’ll guide you step-by-step through setting up a Facebook Developer App, configuring native platforms, and implementing Facebook authentication using the react-native-fbsdk-next
library. By the end, you'll have a working example of Facebook Login that you can easily adapt to your 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:
- React Native
- Node.js (NPM or Yarn)
- react-native-fbsdk module
- React Native Elements
- Facebook Developer Dashboard
- Android Studio or the SDK for Android
- XCode for iOS
- Terminal (OSX/Linux) or Command Line (Windows)
- Text Editor or IDE (We are using VSCode)
Before starting 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
Set up a Facebook App
This step is about setting up or creating 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. Log in 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 clicking the submit button, now, you can see App ID and Secret, write them 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 the iOS bundle ID that will be supplied on XCode later.
Select SDK: Cocoapods as a development environment before using Facebook Login for iOS, then click the Next button.
Enter the iOS bundle ID that will be supplied 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 the 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 fillin 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 the Google Play for the existence of this package name. You can ignore the pop-up 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 a 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 the save and continue button.
Enabled Single Sign-On, then click the Next button a few times until the end of the Facebook Android setup.
Create a React Native App
This time, we will use React Native Community CLI to create a React Native app because the Firebase Cloud Messaging will be used natively. To create it, type this command in your App projects folder.
npx @react-native-community/cli@latest init ReactNativeFacebook
Next, go to the newly created React App folder and run the React Native app on the simulator.
cd ReactNativeFacebook && npx react-native run-ios
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's ready to use with the Facebook App. For Android a little tricky. First, change the source folders which previously were `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 the 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 the </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 was previously created. Next, we have to manually add a few Obj-C codes to make the Facebook App integration work. 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 the 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 by typing this command inside the android folder.
./gradlew build
Next, to add the Facebook App ID to the 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 is added.
<uses-permission android:name="android.permission.INTERNET"/>
Add the 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 at the top of the 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 puts 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 a 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 React Native to React Native FBSDK.
react-native unlink react-native-fbsdk
react-native link react-native-fbsdk
Run the React Native app on the Android device using this command. Make sure the Android device is connected using a USB cable and USB Debugging is enabled so it can be detected using the 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 iOS, we can open the `ios/ReactNativeFacebook.xcworkspace` from Xcode, then use the valid provisioning profile signing, and 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's the React Native Facebook login app. You can find the full source on our GitHub.
That's just the basics. If you need more deep learning about React.js, React Native, or related, you can take the following cheap course:
- Master React Native Animations
- Advanced React Native Topics
- React Native
- Learning React Native Development
- React: React Native Mobile Development: 3-in-1
Thanks!