Facebook Sign In integration in React Native
Here is an example of Facebook Sign In integration in React Native using Facebook SDK. Every application has a login and signup option but if you are integrating the social login into it then it becomes much easier for the users to login without the mess of filing the registration form and confirming via Email or OTP.
As we all know Facebook is a very popular platform so we will see the example to integrate the Facebook login in our App. If you are interested in the more social logins then you can also see Example of Google Sign In in React Native.
To log in, via Facebook feature in React Native, we will use react-native-fbsdk
library which is very simple and easy to integrate. Let’s get started with the Facebook login example.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependency for Facebook Login
To use LoginButton
, AccessToken
, GraphRequest
, GraphRequestManager
we need to install react-native-fbsdk
package/library.
To install this open the terminal and jump into your project
cd ProjectName
Run the following command
npm install react-native-fbsdk --save
This example is updated for the latest React Native version. This command will copy all the dependencies into your node_module directory, You can find the directory in node_module
the directory named react-native-fbsdk
.
CocoaPods Installation
After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but need to install pods. So to install pods use
cd ios && pod install && cd ..
Steps to Integrate Facebook Login/Sign In in React Native
1. Create App in Facebook Console
– To add a “Login via Facebook” feature in our app, we have to register our application package/bundle name at Facebook Console. To do that open Facebook Console and create an App there. You can see the option to create the app in the top right corner.
– You will see the following fields to fill
– After filling the form you will be taken to the landing screen. From there click on the Dashboard option and you will see something like this
2. Update Basic Details and Add Platforms
– Now to click on the Basic under settings and fill the details like Display Name (Which will be the display name at the time of Login Permission), App Logo, etc
– Now if you scroll down a bit then you will see an Add Platform option. We will add Android and IOS platform using it so that we can log in on both the platform
3. Add Android Platforms in Facebook Console
– After clicking on the Add platform you will see Lots of platform options. We will choose Android for the now
– Now you will see an additional Android section at the bottom of the Basic setting section. Please fill the required details.
- Package name from your AndroidManifest.xml file (YourProject > android > app > src > main > AndroidManifest.xml).
- Class Name will be “Package name + MainActivity”.
- For the Key Hashes please follow Getting Key Hash for Facebook Console.
After filling that hit Save changes button.
This is how we have done with the addition of the Android platform in the console. Now we are going to add App ID in our Android code.
4. Add Facebook App Id in Android Code
– After adding the Android platform add the following meta-data in the AndroidManifest.xml file
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id"/>
– Add the App ID in the string.xml file. (You can find the App ID at the top of the Facebook console)
<string name="facebook_app_id">475620579884123</string>
5. Add iOS Platforms in Facebook Console
– To add iOS choose Add Platform option in the developer console and you will see this again
– Open your iOS project in the XCode and copy your Bundle Identifier
– After Clicking on the IOS you will see this form where you have to paste the copied bundle ID and then hit Save changes. This is how we have added IOS platform
6. Some Additional Changes in iOS Code to allow Facebook Via Login
– We need some customization in the iOS project to allow the IOS app to login via Facebook. And for that right-click on the info.plist file and select Source Code. After that, you will see a file like an XML file
– In this file please add the following section at last before </dict> as given in the image below. Please Replace Your Facebook ID (on 2 places)
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb(Replace Your Facebook ID)</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>Replace Your Facebook ID</string>
<key>FacebookDisplayName</key>
<string>AboutReactLogin</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
– Open AppDelegate.m and add the following lines as per the image below
#import <FBSDKCoreKit/FBSDKCoreKit.h>
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
- (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;
}
Huh! Thank you to be with us in this long process. Now we are ready to go to the code.
In this example, we are simply integrating the Facebook login button which will open the Facebook login page or it will directly ask for permission if you have the Facebook app installed and after login, we will display the name, Profile picture, and the token.
User id/Token is the thing which is always the same for a profile so when user login via Facebook you can keep the id in the session and can identify the user every time.
Code for Facebook Sign In
Now open App.js in any code editor and replace the code with the following code
App.js
// Example of Facebook Sign In integration in React Native
// https://aboutreact.com/react-native-facebook-login/
// Import React in our code
import React, {useState} from 'react';
// Import all the components we are going to use
import {
SafeAreaView,
View,
StyleSheet,
Text,
Image
} from 'react-native';
// Import FBSDK
import {
LoginButton,
AccessToken,
GraphRequest,
GraphRequestManager,
} from 'react-native-fbsdk';
const App = () => {
const [userName, setUserName] = useState('');
const [token, setToken] = useState('');
const [profilePic, setProfilePic] = useState('');
const getResponseInfo = (error, result) => {
if (error) {
//Alert for the Error
alert('Error fetching data: ' + error.toString());
} else {
//response alert
console.log(JSON.stringify(result));
setUserName('Welcome ' + result.name);
setToken('User Token: ' + result.id);
setProfilePic(result.picture.data.url);
}
};
const onLogout = () => {
//Clear the state after logout
setUserName(null);
setToken(null);
setProfilePic(null);
};
return (
<SafeAreaView style={{flex: 1}}>
<Text style={styles.titleText}>
Example of Facebook Sign In integration in React Native
</Text>
<View style={styles.container}>
{profilePic ? (
<Image
source={{uri: profilePic}}
style={styles.imageStyle}
/>
) : null}
<Text style={styles.textStyle}> {userName} </Text>
<Text style={styles.textStyle}> {token} </Text>
<LoginButton
readPermissions={['public_profile']}
onLoginFinished={(error, result) => {
if (error) {
alert(error);
console.log('Login has error: ' + result.error);
} else if (result.isCancelled) {
alert('Login is cancelled.');
} else {
AccessToken.getCurrentAccessToken().then((data) => {
console.log(data.accessToken.toString());
const processRequest = new GraphRequest(
'/me?fields=name,picture.type(large)',
null,
getResponseInfo,
);
// Start the graph request.
new GraphRequestManager()
.addRequest(processRequest).start();
});
}
}}
onLogoutFinished={onLogout}
/>
</View>
<Text style={styles.footerHeading}>
Facebook Sign In integration in React Native
</Text>
<Text style={styles.footerText}>
www.aboutreact.com
</Text>
</SafeAreaView>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
textStyle: {
fontSize: 20,
color: '#000',
textAlign: 'center',
padding: 10,
},
imageStyle: {
width: 200,
height: 300,
resizeMode: 'contain',
},
titleText: {
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
footerHeading: {
fontSize: 18,
textAlign: 'center',
color: 'grey',
},
footerText: {
fontSize: 16,
textAlign: 'center',
color: 'grey',
},
});
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
Android
iOS
This is how you can Integrate Facebook Sign In in your React Native Application. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
i facing an issue in release apk of login error. hashkey is not matching . but i have already generated release key and add into my fb account .
Hi salman, I have updated the post. Please try to generate the hash key accordingly.
“i facing an issue in debug apk of login error. hashkey is not matching . but i have already generated release key and add into my fb account .”
i have same issue, i followed your updated post. Still i am not able to sign in successfully.
I have faced the same issue. Please follow the 2nd step of example here https://aboutreact.com/getting-key-hash-for-facebook-console/
Hi, thank you very much for the post and steps.
I am facing an issue after following correctly all the steps above.
what can i do?
Help, please.
AppDelegate.m:13:9: fatal error: ‘FBSDKCoreKit/FBSDKCoreKit.h’ file not found
#import
Can open the project in Xcode for once and install the pod again? This will install the required dependency
Able to get it working for android. However for ios i am seeing “App not setup. This app is still in development mode”. This is weird bcz my app is live and it works fine in android.
Have you tried this?
sir ,how to get email in fbsdk for react native