The Facebook SDK for React Native

Facebook has created itself react-native-fbsdk package: a React Native wrapper around FB SDKs for Android and iOS. Integrating the package into your app can be a challenge of its own, but it’s not the subject of this post. More on this can be found on react-native-fbsdk GitHub docs and on FB getting started docs for React Native SDK.

In this post, we are going to see real examples of how to use this JavaScript React Native API. Unfortunately, official documentation and examples are not very comprehensive yet, making it much harder for RN developers to make use of the package.

How to setup custom Facebook login button

Login Permissions

First of all let’s start with permissions. Facebook has a set of 3 pre-approved permissions, that developers can use to get user data immediately. These permissions are shown below along with their description.

Image 1: pre-approved Facebook login permissions

public_profile permission is the minimum that an application can and must ask, in order for it to be able to use Facebook login — and in return the minimum that a user should authorize, if he wants to login through Facebook.

If you wish to make use of more than these 3 permissions (i.e. user_location, publish_actions etc), then the app must be submitted to Facebook for approval before being released in production.

Login Button

react-native-fbsdk package comes with an out of the box login button which can be imported as a component and simply used inside a render function. It’s a good and fast option that is shown here. In most cases though, developers will have specific UI requirements of how to make the Facebook login button look like (i.e. similar to the other application buttons). Let’s see the example of how the Facebook login button looks like in Math Warriors app:

Image 2: custom Facebook login button in Welcome screen of Math Warriors Android game

JSX looks like this :

<FBButtonWrapper>

<Button

text={I18n.t('welcome.LOGIN_WITH_FACEBOOK')}

width={widthPercentageToDP('59%')}

fontSize={heightPercentageToDP('2.85%')}

onClick={this.facebookLogin}

backgroundColor={colors.blue}

textColor={colors.white}

padding={`${heightPercentageToDP('2.7%')} ${heightPercentageToDP('3.2%')}`}

borderRadius={widthPercentageToDP('10%')}

/>

</FBButtonWrapper>

and is consisted from the FBButtonWrapper styled component and from the custom Button component. It’s a custom implementation, so you can implement it however you want! In the code above we use styled-components package for CSS and I18n package for text translation. widthPercentageToDP , heightPercentageToDP are custom functions built to make app’s UI responsive. For more on this and how to make your RN app responsive in all devices check my article How to develop responsive UIs with React Native.

Moving on, let’s check the functional code that actually does the work in order to login with Facebook!

import {

LoginManager,

AccessToken,

GraphRequest,

GraphRequestManager

} from 'react-native-fbsdk'; async facebookLogin() {

// native_only config will fail in the case that the user has

// not installed in his device the Facebook app. In this case we

// need to go for webview.

let result;

try {

this.setState({showLoadingModal: true});

LoginManager.setLoginBehavior('NATIVE_ONLY');

result = await LoginManager.logInWithReadPermissions(['public_profile', 'email']);

} catch (nativeError) {

try {

LoginManager.setLoginBehavior('WEB_ONLY');

result = await LoginManager.logInWithReadPermissions(['public_profile', 'email']);

} catch (webError) {

// show error message to the user if none of the FB screens

// did not open

}

} // handle the case that users clicks cancel button in Login view

if (result.isCancelled) {

this.setState({

showLoadingModal: false,

notificationMessage: I18n.t('welcome.FACEBOOK_CANCEL_LOGIN')

});

} else {

// Create a graph request asking for user information

this.FBGraphRequest('id, email, picture.type(large)', this.FBLoginCallback);

}

}

Let’s examine the code above us.

First, we import all the modules we will use from react-native-fbsdk package. Then, we manually set the login behavior with the help of LoginManager module. Login behavior property controls what the user will see; either the web FB login screen or the ative FB login screen.

Image 3: web FB login view (on the left) and native FB login view (on the right)

If user inserts credentials and confirms permissions approval, we proceed to fetch his data through a graph request (we will the request closer over the next code section). Else, if user clicks the exit or cancel button, we handle that ( result.isCancelled case in code), by showing a toast message and FB login screen closes automatically.

In order to achieve the optimum user experience we aim for the native FB login view always. That way, FB login will load faster, have native look and will not require from user to provide his credentials from scratch. The only catch here is that in order for this to work, the user needs to have Facebook app installed over his phone. So we set the login behavior to NATIVE_ONLY and if that scenario fails we use a try...catch struct and fallback to WEB_ONLY behavior that opens the web view.

How to perform a Facebook graph request

Now, and after the user has authorized the login process, we need to perform a request to Facebook’s Graph API in order to retrieve the wanted data. This is performed with the use of FBGraphRequest function above. Let’s have a look at the body of the function:

async FBGraphRequest(fields, callback) {

const accessData = await AccessToken.getCurrentAccessToken(); // Create a graph request asking for user information

const infoRequest = new GraphRequest('/me', {

accessToken: accessData.accessToken,

parameters: {

fields: {

string: fields

}

}

}, callback.bind(this)); // Execute the graph request created above

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

}

The above code performs 3 things:

A. get the FB access token with the help of AccessToken module

B. create a graph request with the proper parameters (access token, FB fields we want to query) with the help of module GraphRequest

C. execute the graph request with the help of GraphRequestManager module.

Check out

1. the use of parameter '/me' , which is the user endpoint to query (always the current user)

2. the string format of the passed arguments when creating the graph request ( 'id, email, picture.type(large)' ). The graph request arguments need to be passed as one string, where each parameter is separated by coma. If you want to query another parameter, identify it from the Graph Request API reference and convert the object specified there to string. The conversion is performed by joining keys with dots ( . ) and by providing the final level value as argument. I.e. user parameter picture, is represented in the FB graph as an object:

picture: {

type: 'large'

}

and is converted to the parameter string like that: picture.type(large) .

Finally, when executing/starting the graph request API call we also provide a callback function that handles the result of the call. The function will either retrieve and save the requested data or show an informative toast message to the user in case of an error.