React Native Facebook Login

Kyle Buntin
2 min readDec 22, 2020

Social media Authentication like Facebook login is becoming necessary while building the authentication flow of a mobile app. In React Native, this can easily be achieved in a few minutes.

Requirements

  • expo-facebook

Go ahead and install expo-facebook dependency with:

expo install expo-facebook

The only method you need

import * as Facebook from 'expo-facebook';Facebook.initializeAsync({ appId: 'APP_ID',});const logInWithFacebook = async () => {try {const {type,token,expirationDate,permissions,declinedPermissions,} = await Facebook.logInWithReadPermissionsAsync({permissions: ['public_profile'],});if (type === 'success') {// Get the user's name using Facebook's Graph APIconst response = await fetch(`https://graph.facebook.com/me?access_token=${token}`,);Alert.alert('Logged in!', `Hi ${(await response.json()).name}!`);} else {// type === 'cancel'}} catch ({ message }) {alert(`Facebook Login Error: ${message}`);}};

(If you need an already implemented solution with a cool UI, check out this free mobile template at QuickComponent where Facebook login is implemented.)

With a valid Facebook application ID in place of APP_ID, the code above will prompt the user to log into Facebook then display the user’s name. This uses React Native’s to query Facebook’s.

Valid methods you can always call on Facebook include:

Facebook.logOutAsync() available to logout currently authenticated user

Facebook.getAuthenticationCredentialAsync() — return the authenticated user credentials if exist and null if no user exists.

For more information on other methods, you might need, visit the official documentation of expo-facebook here

Also, get a free template with Facebook Login already implemented and other premium templates with the complete backend at QuickComponent.

Originally published at https://www.quickcomponent.com on December 22, 2020.

--

--