Search
  • Kyle

React Native Facebook Login

Updated: Dec 23, 2020


photo by William Iven from Unsplash


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 API
     const 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 fetch to query Facebook's Graph API.


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.


This post was inspired by the Facebook login project on react native templates here and also the post on react native Facebook login.



#reactnative #facebook #login #mobileapp

20 views0 comments