Codementor Events

Configuring React Native Facebook Authentication

Published Nov 24, 2020Last updated May 22, 2021
Configuring React Native Facebook Authentication

In this tutorial I would love to take you through the steps of how to set up Facebook and Google Social login in your React Native application.

Facebook Login

Implemtenting Facebook Login might sound difficult but is really easy.

Setting up social login in your application is in registering your Facebook App IDs and Google Client IDs on the console are the first steps to this implementation.

Now lets do this.

Setting up an App ID for Facebook

This is an ID used to get authorisation for using the Facebook API to login to your app. Please visit https://developers.facebook.com to login.

Steps:
Create a new app and register a new Facebook App ID.
Add Platforms android and ios (as needed)

For IOS, add your bundle ID while for Android, do add your package name and key hashes

Setting up for Expo User

This will require installing this package.

$ expo install expo-facebook

In your login screen, do add the Facebook login button
import BlockButton from '../buttons/BlockButton';



<View style={styles.authButtonView}>
  <BlockButton title="Start" onPress={handleStartPress} />
  <View style={styles.socialButtonsView}>
    <BlockButton title="Facebook" onPress={handleFBLoginPress} />
  </View>
</View>

Also be sure to initiate the permissions in the useEffect affect configuring your facebook App ID.

import React, { useEffect, useState, useContext } from 'react';
import * as Facebook from 'expo-facebook';

import { FB_APP_ID } from '../config/constants';


const initSocialLogin = async () => {
  try {
    await Facebook.initializeAsync(FB_APP_ID);
  } catch (e) {
    console.log(e);
  }
};


useEffect(() => {
  initSocialLogin();
}, []);

Final Code Implementation

With intentions of generating expo stand-alone builds, you must add facebookScheme, facebookAppId, andfacebookDisplayName to your app.json file as seen in the Facebook documentation (step 4) .

Now, let us update our Login component.

import { FB_APP_ID } from '../config/constants';

//...

export const fbLogin = async () => {
  try {
    const { token, type } = await Facebook.logInWithReadPermissionsAsync(
      FB_APP_ID,
      {
        permissions: ['public_profile'],
      }
    );

    // GET USER DATA FROM FB API
    const response = await fetch(
      `https://graph.facebook.com/me?access_token=${token}`
    );
    const user = await response.json();

    // GET PROFILE IMAGE DATA FROM FB API
    // NOTE THAT I SET THE IMAGE WIDTH TO 500 WHICH IS OPTIONAL
    const pictureResponse = await fetch(
      `https://graph.facebook.com/v8.0/${user.id}/picture?width=500&redirect=false&access_token=${token}`
    );
    const pictureOBject = await pictureResponse.json();
    const userObject = {
      ...user,
      photoUrl: pictureOBject.data.url,
    };

    return { type, token, user: userObject };
  } catch (e) {
    return { error: e };
  }
};

const handleFBLoginPress = async () => {
    const { type, token, user, error } = await fbLogin();

    if (type && token) {
      if (type === 'success') {
        // DISPATCH TOKEN AND USER DATA
        // TO HANDLE NAVIGATION TO HOME AND DISPLAY USER INFO
        dispatch({ type: 'FB_LOGIN', token, user });
      }
    } else if (error) {
      console.log('The login attempt was cancelled');
    }
  };

Conclusion

Incases where you want to make your login public, enable Production mode in the Facebook developer console.

Happy Coding.

Discover and read more posts from Olebuezi Obinna David
get started
post comments2Replies
Alex Rock
2 years ago

thanks for the awesome information.

Real Enemy Strike FPS
4 years ago