Archilo: helping architecture work become visible.

Explore the ecosystem →

Updates & announcements

Archilo: helping architecture work become visible.
Archilo: helping architecture work become visible.

A focused platform for architecture portfolios, research, talent and creative opportunity. Built for architects, students and studios.

Enally announcement
Enally: building useful things, together.

A founder-led ecosystem connecting products, services, knowledge, community and opportunities. One belief, expressed in different ways.

Enally announcement
Build with us: internships, contributors and partnerships.

Practical ways for young builders, contributors and domain experts to learn through real products and useful responsibility.

Archilo growing steadily
Archilo growing steadily

Architecture portfolios and research pages now serve 5,000+ creative professionals.

Enally announcement
Humble campus expansion

Verified student communities now active across multiple campuses with 2K+ members.

Faaho partner beta live
Faaho partner beta live

Zero-brokerage living discovery is now available in partner beta. Technology by Enally.

Enally announcement
Enally Labs launched

Applied AI experiments, internal agents and prototype products now live under Labs.

Enally announcement
Blog redesigned

The Enally blog now brings practical guides, opportunities and ecosystem knowledge together.

Enally announcement
Services: SEO to AIO

Five-layer visibility services now available — SEO, AEO, GEO, SXO and AI Optimization.

Enally announcement
Build with us program

Internships, campus ambassadors and contributor roles open for builders who want real ownership.

Enally announcement
Company website rebuilt

Enally.in redesigned with improved performance, accessibility and dark theme support.

Tech

How to integrate Facebook Login API into your React or Other App v7.0 and Above

Guidance on implementing Facebook Login API into various applications, such as React or others. It outlines three distinct methods: utilizing the SDK, integrating with Firebase Auth using Facebook authentication provider, and setting up Facebook Manual login.

How to integrate Facebook Login API into your React or Other App v7.0 and Above
What you'll learn

Guidance on implementing Facebook Login API into various applications, such as React or others. It outlines three distinct methods: utilizing the SDK, integrating with Firebase Auth using Facebook authentication provider, and setting up Facebook Manual login.

Introduction

In today's interconnected world, providing users with the convenience of social media login options can significantly enhance the user experience of your application. Facebook Login API offers a seamless way for users to sign in to your app using their Facebook credentials. In this guide, we'll explore three different approaches to integrating Facebook Login API into a React app. We'll cover using the SDK, leveraging Firebase Authentication with Facebook, and setting up manual login steps.

Prerequisites

Before we dive into the implementation, ensure you have the following:

  • Facebook Developer Account: You need to have a Facebook Developer account to create and manage your Facebook apps. Facebook for Developers

  • Facebook App: Create a Facebook app in both normal and business mode. This allows you to access different features based on your app's requirements.

Setting Up Facebook Authentication

  1. Create a Facebook App:

    • Log in to your Facebook Developer account and navigate to the Developer Dashboard.
    • Click on "Create App" and follow the prompts to create your app.
    • Configure your app settings, including the platform (web), basic information, and contact email.
  2. Configure Auth URL and Callbacks:

    • In the Facebook Developer Dashboard, go to your app settings.
    • Under "Settings" > "Basic," configure the "App Domains," "Site URL," and "Privacy Policy URL" fields.
    • Add platform-specific OAuth redirect URIs for your React app.
  3. Retrieve App Credentials:

    • Once your app is created, note down the App ID and App Secret. You'll need these credentials to integrate Facebook Login into your React app.
  4. Enable Facebook Login:

    • In your Facebook Developer Dashboard, navigate to "Products" > "Facebook Login."
    • Enable Facebook Login and configure settings such as OAuth redirect URIs and permissions. Facebook Login Documentation

Implementation

Now let's dive into the code implementation for each approach:

Using SDK:


 

javascript

// LoginWithFB.js
import React, { useContext } from 'react';
import FacebookLogin from 'react-facebook-login';
import { LoginAuthContext } from '../Auth/loginAuthContext';

const LoginWithFB = () => {
    const { setAccessToken, setUserID } = useContext(LoginAuthContext);

    const responseFacebook = async (response) => {
        try {
            await setAccessToken(response.accessToken);
            await setUserID(response.userID);
            console.log(response);
            if (response.status !== 'unknown') {
                alert('Login Successful');
            } else {
                alert('Login Failed');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('Login Failed');
        }
    }

    return (
        <div>
            <FacebookLogin
                appId="XXXXXXXXXXXXXXXX"
                autoLoad={false}
                fields="name,picture"
                callback={responseFacebook}
            />
        </div>
    );
};

export default LoginWithFB;

 

Firebase Authentication with Facebook:

1. Enable Facebook Auth Provider


2. Add these:

3. Add oAuth uri and others

javascript

// LoginWithFB.js firebase
import React, { useContext, useState } from 'react';
import FacebookLogin from 'react-facebook-login';
import { LoginAuthContext } from '../Auth/loginAuthContext';
import { FacebookAuthProvider, signInWithPopup } from "firebase/auth";
import { auth } from '../../firebase';

const LoginWithFB = () => {
    const { setAccessToken, setUserID } = useContext(LoginAuthContext);
    const provider = new FacebookAuthProvider();
    const [userData, setUserData] = useState({});

    const handleFacebookLogin = (response) => {
        signInWithPopup(auth, provider).then((result) => {
            const credential = FacebookAuthProvider.credentialFromResult(result);
            const accessToken = credential.accessToken;
            setAccessToken(accessToken);
            setUserID(result.user.uid);
            setUserData(response);

            console.log('response', response);

            alert('Login successful');

        }).catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            const email = error.email;
            const credential = FacebookAuthProvider.credentialFromError(error);
            console.log(errorCode, errorMessage, email, credential);
        });
    }

    return (
        <div>
            <button className="btn" onClick={handleFacebookLogin}>Login with Facebook</button>
        </div>
    );
};

export default LoginWithFB;

// firebase.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export { auth };

 

Manual Login Setup:


 

javascript

// LoginWithFB.js
import React, { useEffect } from 'react';

const LoginWithFB = () => {
    useEffect(() => {
        window.fbAsyncInit = function() {
            FB.init({
                appId: 'YOUR_APP_ID',
                cookie: true,
                xfbml: true,
                version: 'v8.0'
            });

            FB.AppEvents.logPageView();

            FB.getLoginStatus(function(response) {
                statusChangeCallback(response);
            });
        };

        // Load the Facebook SDK asynchronously
        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) { return; }
            js = d.createElement(s); js.id = id;
            js.src = "https://connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));
    }, []);

    const statusChangeCallback = (response) => {
        console.log('statusChangeCallback');
        console.log(response);
        if (response.status === 'connected') {
            console.log('loggedin');
            FB.api('/me', function(response) {
                console.log('Successful login for: ' + response.name);
                document.getElementById('status').innerHTML =
                    'Thanks for logging in, ' + response.name + '!';
            });
        } else {
            document.getElementById('status').innerHTML = '';
        }
    };

    const handleFacebookLogin = () => {
        FB.login(function(response) {
            statusChangeCallback(response);
        });
    };

    return (
        <>
            <button onClick={handleFacebookLogin}>Login with Facebook</button>
            <div id="status"></div>
        </>
    );
};

export default LoginWithFB;

 

Packages required for different methods:

  • Using SDK: npm install react-facebook-login
  • Firebase Authentication with Facebook: npm install firebase

Advanced Access for Facebook Login for Business

To use Facebook Login for Business and access advanced features, follow these steps:

  1. Go to the App review menu on Facebook Developer Dashboard, then navigate to Permissions and features.
  2. Click on "Get advanced access for the public_profile permission."
  3. Confirm Advanced Access for public_profile.
  4. Check the box agreeing to use any data received through public_profile in accordance with allowed usage.

Conclusion

Integrating Facebook Login API into your React app offers a convenient way for users to sign in and engage with your application. By following the steps outlined in this guide, you can seamlessly implement Facebook authentication using different approaches, catering to your app's specific requirements. Whether you choose to use the SDK, Firebase Authentication, or set up manual login steps, providing users with the option to sign in with Facebook can enhance user experience and streamline the authentication process.

Frequently asked questions

Guidance on implementing Facebook Login API into various applications, such as React or others. It outlines three distinct methods: utilizing the SDK, integrating with Firebase Auth using Facebook authentication provider, and setting up Facebook Manual login.

The estimated reading time is 8 min read.

Keep learning

Related articles