How to add Facebook login to a React-Native app

11 min readApr 11, 2020


It is a friday night and I am listening to “Trappin in Japan 14” which is one of my favourite lo-fi mixes and I thought it would be cool to write a tutorial about one of the features I have always wanted to implement into an app, that is, integrating a facebook login into an application. Let’s goooo (This is for react native projects 0.60 and greater)

The first you will need to do obviously is create a new react-native application in your location of choice.

Step 1. Create react-native project

react-native init facebookapp

The next step is to open this project in your favourite code editor and in the terminal of the code editor enter the below.

Step 2. Install facebook sdk package

npm install react-native-fbsdk

This will install the Facebook SDK that contains the necessary components we need in order to login to facebook via our app

After this has finished installed we need to link the dependencies using the below

react-native link react-native-fbsdk

Once you have done this in the terminal enter the below

cd ios
pod install

We switch to our ios directory and install the cocoa dependencies for iphone

Step 3. Create facebook app

Now we have got our basic setup we will need to login to Facebook for Developers using our facebook account and create a new app on there.

Once you have logged on you will see on the right it has a heading called “My apps”, click on this and then click “create app”, you will then be able to give a display name for your app. I will just call mine react native test.

You should now see a dashboard and have a unique app id for your app.

Now you will need to locate to the basic settings page which can be located by clicking on the “Settings” button on the left pane and then clicking “Basic” from the options that show.

Scroll down to the bottom of this page there should be a clickable bar that spans across the width of the page with the text “Add platform”, click this and then click IOS.

A new menu should open which requires you to enter info such as bundle ID. To get this info we need to go to our xcode project that was generated when we made this whole react native project.

To find the “bundle id” you will need to open the xcworkspace file from your project in xcode then click on your projects name on the left hand pane and then you should see a menu showing items such as “display name”, bundle identifer, version and build. Copy the content inside the bundle identifier. Once you have done this, paste the content inside the bundle id text box and click save, the bundle id is the only mandatory field in that section.

Furthermore, scroll to the bottom of the page again if you want to login to facebook via an android app as well you will be greeted with a similar dialog container. With android you are required to enter a class name and google package name, to see this you will need to open the build.gradle file within the “app” folder of your project and get the application id and the class name whch will be the app id plus MainActivity i.e. mine is com.newsfeed.MainActivity.

NOTE: If you wish to publish the app to the app store you will also need to add key hashes to the relevant text boxes on this dialog box on the facebook app too.

ANOTHER NOTE: If you see a popup saying “there was an error with the package name” don’t worry about this and just click “use this package name”

Now click “save changes”

Our last process before making our facebook app live is to add a privacy policy, you can go to one of the various privacy policy generator websites for now, this isn’t too important for this tutorial as i won’t be going live with this, however, if you are going to go live with an app that uses facebook login it is incredibly important you spend time and do your research on privacy policies and how much user information you collect.

Here is a link to help get you started

Once you have got the link for your privacy policy just paste it into the privacy policy textbox on the facebook app dashboard.

To switch our app to live we need to click on the switch at the top where it says “in development”, then in the popup that appears after clicking it press “switch mode”.

Configuring Android project

To ensure our login button works on an android project we need to add a value to the strings.xml file found within the values directory of the android project.

One of these is the facebook app id so you will need to create a new string inside this file with the name set to “facebook_app_id” and the value of this string set to your facebooks app id.

The next step is to open the androidmanifest xml file (which contains information about your project including activities, components and packages) which can be found in the “app/src/main” path of your project and if the “INTERNET” permission is not already present in the file then you will need to add it. Adding this enables your app to ask for permission to use the internet from your app.

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

You will need stay within your manifest file for now and add a meta-data attribute that references the new string value of your facebook app id you created earlier. That is it for configuring your android project for facebook sdk.

Apple IOS Configuration

The first thing you will need to do is add a bunch of values to the info.plist of your project in xcode. (remember to open the xcworkspace file of your project in xcode) The info.plist file is to help an app provide meta data to its system through the use of properties the file suffix is short for “information property list”.

Copy the below code into the info.plist just prior to the last “dict” element and replace the app id and app name with your values from the dashboard of your facebook app.

Remember to remove the “{“ and “}” where it says “app-id” i made the mistake of leaving them in lol

<array> <dict>

Below is just a screenshot so you know where to put the code in the info.plist file

The next step is to add the below some code to the AppDelegate.m file

The first piece of code to add is the importing of the Facebook SDK kit at the top of the file.

#import <FBSDKCoreKit/FBSDKCoreKit.h> - (BOOL)application

Now you will need to add the below code after the “didFinishLaunchingWithOptions” method

- (BOOL)application:(UIApplication *)applicationopenURL:(NSURL *)urloptions:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:applicationopenURL:urlsourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];// Add any custom logic here.return handled;}

NOTE: An optional piece of code can be added to the “didFinishLaunchingWithOptions” method which is only required if you are not using the latest FBSDK

[[FBSDKApplicationDelegate sharedInstance] application:applicationdidFinishLaunchingWithOptions:launchOptions];//only need the 2 above lines if you are not using the latest sdk version

Now that we have finished adding in platform specific code we can go ahead and start writing some JavaScript!

Adding in JavaScript code for login button

So now head to your App.js file of your react native project

The first step you will need to do is import various components from the ‘react-native-fbsdk’ package. These include LoginButton, AccessToken, GraphRequest and GraphRequestManager.

LoginButton — The login button component

AccessToken — Component that has various methods for getting and accessing access tokens

GraphRequest — GraphRequest is a single request that is sent to the Facebook platform through the Graph API, it contains functionality that can serialize and deserialize information from requests and responses. GraphRequests can be sent anonymously, and in that case it does not need an access token to be sent with the request. However, if you wish to send a request aunthenticated then an access token must be sent along with the request.

import {LoginButton,AccessToken,GraphRequest,GraphRequestManager,} from 'react-native-fbsdk';

After importing the necessary components we will create an object inside of our state called “myInformation” which will be an object that contains the returned information from the graph request.

state = {myInformation: {}};

We now need to create a method that retrieves information from a graph request that contains an access token.

Create a method called “GetInformationFromToken” which takes in one parameter named “accessToken”.

Inside of this method you will need to create an object that contains a key named “fields” and the value for this key is another object with a key of “string” and the values for that is one string which contains the fields you want to return from the graph request separated by commas.

const parameters = {fields: {string: 'id, first_name, last_name, middle_name',},};

In addition, the next step is to create a const that contains a GraphRequest. As i explained earlier, a graph request is a request sent to Facebook via the graph API, however, this request can take a multitude of parameters including path, access token, parameters and callback.

For this tutorial i will be retrieving information about myself so I will set the first parameter (which is the path) as ‘/me’ like below

const myProfileRequest = new GraphRequest('/me',

Our next parameter is going to be an object that contains our “accessToken” parameter, and then pass in the parameters that we have defined earlier in our object

const parameters = {fields: {string: 'id, first_name, last_name, middle_name',},};const myProfileRequest= new GraphRequest('/me',{accessToken, parameters: parameters},

After adding this we will add a callback that will contain information about the response of the request and error information. We then do a basic error check and if no errors then we set the “myProfileInfoResult” parameter to the state “myInformation”. So now our request looks like the below

const myProfileRequest = new GraphRequest('/me',{accessToken, parameters: parameters},(error, myProfileInfoResult) => {if (error) {console.log('login info has error: ' + error);} else {this.setState({myInformation: myProfileInfoResult});console.log('result:', myProfileInfoResult);}},);

The final bit of code that needs to be added to this method is to add the request to a graph request manager which starts the request

new GraphRequestManager().addRequest(myProfileRequest).start();

So now our method looks like this

GetInformationFromToken = (accessToken) => {const parameters = {fields: {string: 'id, first_name, quotes',},};const myProfileRequest = new GraphRequest('/me',{accessToken, parameters: parameters},(error, myProfileInfoResult) => {if (error) {console.log('login info has error: ' + error);} else {this.setState({myInformation: myProfileInfoResult});console.log('result:', myProfileInfoResult);}},);new GraphRequestManager().addRequest(myProfileRequest).start();};

Now we move onto writing code inside of the render method, delete all of the stuff that react native autofills the render method with when it first generates the project and replace it for now with a basic View and maybe add some text

<View style={{flex: 1, margin: 50}}><Text>My react native facebook login app</Text></View>

Below the text tag incorporate the LoginButton component and we will be using 2 callbacks methods inside of this component, these “OnLoginFinished” and “OnLogoutFinished”, the purpose of them is self-explanatory.

Inside of “OnLoginFinished” we write 2 parameters for the callback, one containing error information and one that contains other properties we may want to use after we have logged in. We will do a simple error check as well as a check if the login is cancelled.

<LoginButtononLoginFinished={(error, result) => {if (error) {console.log('login has error: ' +error);} else if (result.isCancelled) {console.log('login is cancelled.');} else {

If none of the these conditions have occurred we will then need to retrieve an access token using the “AccessToken” component within the “react-native-fbsdk” package and call the method “getCurrentAccessToken” this does what it says on the tin (a British phrase) and we then use a promise on this method call with one parameter for the callback named “myData”, this will contain an object named “accessToken” which we access and put inside of a variable named “accessToken”. We then set this variable as the argument for the parameter of the method “GetInformationFromToken”.

<LoginButtononLoginFinished={(error, result) => {if (error) {console.log('login has error: ' +error);} else if (result.isCancelled) {console.log('login is cancelled.');} else {AccessToken.getCurrentAccessToken().then(myData => {const accessToken = myData.accessToken.toString();this.GetInformationFromToken(accessToken);});}}}

When the user logs out we don’t want the state to keep the information, so we also need to set the state in the “onLogoutFinished” method to an empty object.

onLogoutFinished={() => this.setState({myInformation: {}})}

Our final thing to do is prove that we have logged in by displaying info on the app in between a text tag. The below code will retrieve first_name and middle_name of the user via the state, as earlier we set the state “myInformation” to equal to the response of the request.

<Text style={{fontSize: 16}}>Logged in As {this.state.myInformation.first_name} and my middle name is {this.state.myInformation.middle_name}</Text>

I believe to access more personal information such as email, birthday and posts you need to assign a role to a facebook user on your app, but that is out of reach for this tutorial.

After you have written the code above, give your project a run with

react-native run-ios

You should see a facebook login button and click it, you should see a dialog, click continue, you will be asked to enter your facebook credentials if you haven’t already

Ok, phew! that was a long and arduous article but a fun one!

I hope you have learned something from this article, once again if you think I could do anything better then please do say so as I want to get better and improve at article writing, remember to give a clap or share if you liked it ha ;) and stay safe out there :)

Check out my blog —