Facebook Login tutorial for React Native
A straightforward approach without using any wrapper of creating Facebook Login for your React Native app that works for both iOS and Android.
NOTE: I’m not going to implement it using firebase and it is implemented using React Native CLI project and some things might be different for people who have created the react project with Expo. The support for react-native-fbsdk
was discontinued back in January so we won’t be using that but instead, I’ll be using react-native-fbsdk-next
DISCLAIMER: As always Facebook being the worst API out there caused a lot of problems but finally it starts to work, so I’ll advice that you follow each and everything exactly even where I’ve place a line of code (yes, doesn’t make sense but I would not risk it) 😬
Installing the Facebook SDK package
Open your React native project, I’m using VSCode and from the terminal install:
npm install --save react-native-fbsdk-next
Then run this command:
npx pod-install
As I created a fresh project so my pod-install
command will install a lot of stuff, but the important thing is if these four are installed:
Installing FBSDKCoreKit (9.0.1)
Installing FBSDKLoginKit (9.0.1)
Installing FBSDKShareKit (9.0.1)
Installing react-native-fbsdk-next (4.0.0)
That’s it for react-native now. Let move towards configuring the Facebook developer account and our iOS and Android settings.
Setting Up Facebook Developer Account & Keys
Assuming you have created a React Native project at this point.
Open https://developers.facebook.com/ and create an account. Create a new app and you’ll land on this page:
The important thing here is your App ID. From the menu on the left side open Settings → Basic
Make sure to add have all the basic things added for example a privacy policy URL, Verification is done and you have added data protection officer contact information on this basic setting before moving forward.
NOTE: You’re about to start the setup for iOS and Android. If you face an error in the setup please refer to the Possible errors section at the end of this article as the answer might be there.
iOS Setup
Open your iOS project (.xcworkspace) in XCode at this point.
When you scroll down on the basic settings page (on Facebook Developer) you’ll see + Add Platform
Let's start with iOS. Select iOS and add your Bundle ID (As per your iOS project) and you can leave the rest of the fields blank and options to default and turn on the Single Sign-On option.
Click on Save Changes and move back to XCode.
OpenAppDelegate.m
and import
#import <FBSDKCoreKit/FBSDKCoreKit.h>
Then in didFinishLaunchingWithOptions
add this line
[[FBSDKApplicationDelegate sharedInstance] application:applicationdidFinishLaunchingWithOptions:launchOptions];
Right after the above function ends add this function
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
if ([[FBSDKApplicationDelegate sharedInstance] application:app openURL:url options:options]) {
return YES;
}
return NO;
}
Right-click on your project folder and select New File
Select Swift File and click on Next.
Keep the name as File and click on Create
VERY IMPORTANT STEP!!! When you’ll get this popup asking to create a bridging header select Create Bridging Header
It’ll create a blank File.swift
as well as another bridging file.
Now right-click on Info.plist
file → Open As → Source Code
Paste the following code before the last </dict>
(Please see this if there is any issue in this step)
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb292903812235444</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>292903812235444</string>
<key>FacebookDisplayName</key>
<string>RNLoginExampleApp</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
MAKE SURE YOU UPDATE YOUR FACEBOOK APP ID AND DISPLAY NAME IN THE CODE ABOVE.
Save everything and close XCode.
Android Setup
Open react native app in VSCode if you closed it at this point.
Go back to the basic setting page on the Facebook Developer site and click on + Add Platform and select Android.
From react native project open /android/app/src/main/AndroidManifest.xml
and copy the package name and paste it where it’s asking for Google Play Package Name.
For Class Name add .MainActivity
next to your copied package name.
Now we need to add Key Hash in the Key Hashes field. To get a key, run this command from the VSCode terminal:
cd android
Next, run this command
keytool -keystore app/debug.keystore -list -v
It’ll prompt you for the password, so enter android
(that’s the password)
From the response that you’ll get from the above command just copy the SHA1 key
Paste the copied key in the Key Hashes field and press Save Changes. (It’ll hide the key when refreshed but don’t worry it’s there.
If it promotes you for Google Play Package Name, click Use this package name
Now back to VSCOde again, if you closed it open the AndroidManifest.xml
file again and make. sure you have this line in it
<uses-permission android:name="android.permission.INTERNET" />
Then add this line right above </application>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
Next, add this line after ...android:theme="@style/AppTheme>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
Next, open /android/app/src/main/res/values/strings.xml
file and add this line to it:
<string name="facebook_app_id">292903812235444</string>
MAKE SURE YOU UPDATE YOUR FACEBOOK APP ID IN THE CODE ABOVE.
That’s it for android settings.
If you’re facing any error like “SDK has not been initialize” or others, scroll down to Possible Error section to see if that helps.
Next, we’ll finally implement the login.
React Native Implementation
Now that we have everything set up we’re ready to start implementing the Facebook login for our react native project.
Open App.js
(Or any other file like if you have a Login.js
file where you have login screen functionality open that) and remove all the code in App.js
with this
import React from 'react';import { Button, Text, View } from 'react-native';import { LoginManager } from 'react-native-fbsdk-next'function App(props) {return (<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}><Text>Facebook Login React Native Example</Text><Button title={'Login with Facebook'} onPress={() => {LoginManager.logInWithPermissions(["public_profile", "email"]).then(function (result) {if (result.isCancelled) {alert("Login Cancelled " + JSON.stringify(result))} else {alert("Login success with permisssions: " + result.grantedPermissions.toString());alert("Login Success " + result.toString());}},function (error) {alert("Login failed with error: " + error);})}} /></View>);}export default App;
In the code above I’ve simply added a Button
component and in the onPress
I’ve implemented the Facebook login call.
Moment of Truth
Now, it’s time to test it. First, run the app on iOS (Make sure you’re not in the android
folder in terminal if you are then first do cd..
) by typing npx react-native run-ios
or react-native run-ios
in terminal.
And now for android npx react-native run-android
Possible Errors:
- On android, if you see The SDK has not been initialized, make sure to call
FacebookSdk.sdkInitialize()
first.
Solutions on the internet as there might be deprecated so be careful while solving the above. How I solved it? well check your AndoidManifest.xml
again and make sure you're not missing anything especially this line <meta-data android:name=”com.facebook.sdk.ApplicationId” android:value=”@string/facebook_app_id”/>
(You can refer above when we are configuring android)
After that thanks to Asif Iqbal comment on this tutorial, you also need to add facebookSdkVersion
in android/build.grapdle
to avoid SDK has not been initialized error.
buildscript {ext {…facebookSdkVersion = “13.1.0”…}
2. If you’re unable to run the app on iOS and get a really long error log and can’t seem to figure out what is wrong, check if you did that File.swift
step correctly, as you need to create bridging headers in order to make. it successfully runs on iOS.
3. Thanks to Vipulchakravarthy for this solution.
If you’re facing this error after following all the steps for iOS:
use of undeclared identifier 'FBSDKApplicationDelegate'
To solve this In the AppDelegate file Instead of this #import <FBSDKCoreKit/FBSDKCoreKit.h>
try importing the swift file #import <FBSDKCoreKit/FBSDKCoreKit-swift.h>
4. Thanks to Anshul Saxena question on this tutorial you might run into an error that states Feature Unavailable: Facebook login is currently unavailable for this app, since this app does not have Advanced public_profile permission
on android and one possible solution for that would be if you look at the middle android screenshot above you’ll see the small warning. You need to submit your app for review, although Facebook specifies here https://developers.facebook.com/docs/facebook-login/android/permissions/ that “If your app asks for more than the default public profile fields and email, Facebook must review it before you release it.” but I’m not sure why they would show that as we’re only asking for public profile and email. So, that’s one fix of the issue.
As always if you find this helpful share and press the 👏🏻 button so that others can find it too. If you see a typo feel free to highlight it or if you’re stuck drop a comment and I’ll try my best to help you.
All my tutorials are free but if you feel like supporting you can buymeacoffee.com/chaudhrytalha
Happy Coding 👨🏻💻