How to integrate Facebook Login API into your React app
Tags: react, loginapi, facebook, javascript
Published: 2021-03-29 03:52:44

Today, we're going to learn how to integrate Facebook login API into your React app. Why do we need that? According to data from [oberlo](https://id.oberlo.com/blog/facebook-statistics), Facebook is one of the social media which has more than 2.8 billion active users every day. Where this number is spread across Facebook's main business, namely Facebook, WhatsApp, Instagram, and Messenger. 

One of the ways to attract new users to register is that users can easily register. By utilizing a large number of active users on Facebook and integrating Facebook login API into our website, it will increase the probability of increasing users on our website by simply doing one tap on sign up that are already integrated with existing accounts on Facebook.

This article was originally posted at: [https://www.quod.ai/post/how-to-integrate-facebook-login-api-into-your-react-app](https://www.quod.ai/post/how-to-integrate-facebook-login-api-into-your-react-app)

**Objectives**
--------------

In this tutorial, we will show you how to:

1.  Set up a Facebook App
2.  Create React.js App
3.  Install Package "react-facebook-login"
4.  Adding Facebook login to our React app
5.  Run React App to Facebook Login
6.  Run our React App to login with Facebook  
    

**1\. Set up a Facebook App**
-----------------------------

In this tutorial, we will use several frameworks, tools and modules as below.

1.  Node.js. In this tutorial, we are using version 14.15.5. If you have not installed, you can download it from [https://nodejs.org/en/download/](https://nodejs.org/en/download/)‍
2.  react-facebook-login package from npm (node package manager)
3.  React.js. We use version 17.0.1. Before create React App you must install “npx“ package. If you have not installed, you can following this website [https://www.npmjs.com/package/npx](https://www.npmjs.com/package/npx)‍
4.  Text Editor or IDE (We recommend using Visual Studio Code)
5.  Terminal   
    

After all the requirement are available, we need to register as a Facebook Developer Apps. To register, we need to log in using your existing Facebook account at [https://developers.facebook.com/apps/](https://developers.facebook.com/apps/) . If you haven't logged in to Facebook, you will be asked to enter your email or mobile number and password.

  
![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d9105a1028217d4b69417_j2O1lyMYf2Q6aDi7EOYzadx4PNsJDloMjd6pZFnsizl1Y73WDcMZEKmcYNLC_WF5mPs243UUw5A5CfwwNlyWAF0Z5yiSwKKr3mJty3fvj_YR2WjD_iKWXvcYAYWQeQ3u3K4UYlR6aLMh8hardA.png)

After that, you will redirect to [https://developers.facebook.com](https://developers.facebook.com) and click “Get Started” if the first you register at Facebook Developer Apps.

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d9105fcd5f68470dbbd99_bYadGVH08F94fx823XLIqHkM8H3bpgfNRB8wDWap1We45HhpgFbvQRd6eByqrQIMLVjcgz-fsOB27rrZKPtaBB4mQzjmuil9mZ1__D5gr7nlpC6HKmui0IfAWHbm9rnoRK05Yac6x-VGac7gtA.png)

  

You will be taken to the registration dashboard , and click “Continue”

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d9105371fba2bfe685cfe_zJrQJeh73G7xmJbAVuXgXim9Q8f6OFTzZ7sCT3XkI2If3EmSwPgffVfFuBRW04G4WH-BpaLEng-YNRq-OUgHTSw0qhZX_6DS336_t3nAp1lWuYNIWtVnitdeDrqrCjmtDLTFRY-lRPOnukRPHA.png)

  

Fill container of Primary Email with your email other than the Facebook account email that has been registered

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d9105c3adedba254606e8_B0OCghrsYytSoMmpVcQl7vcEe0edl-uhFcJUNLpw0oN20M9mNM9OvsPKnYrULdYOlwwYIyZVeHBrfPbzFt482MKiMuj773coxMWl1YhCvhsbPCiR10askyVCZD_Ngn8WzqRn9Y4aSa1EdsTZ9w.png)

You will get an email code from Facebook. Fill that container with the code you got earlier.

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d910511a38ee785823f6b_eO27eYE_MBeYJZisCuVIomonnzKSBsJjtINn0-PldNyn1lf9b-Chk_ScD1FvCX7qWnO6nGx5klNCBWnzN2VtAVEGW4v_SGURKir4Bk-2lHd9teVIHGAL2AtOs1rCwA5WpQ2D7vNAY1wTQGLSOw.png)

  

Choose as “Developer” and the press button “Complete and Registration”

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d9106c3adeda6d54606e9_b-Bta2iUooLH-v4mDMNKMsy_2ye3heV45JN6YYW9cnAgT40eiYKzYXar6VjA7F3QZRYzyGFMrU3v-jdSCEgFFbzrYfb-1JEOPfjqHZev4uIC4q-gXlsBcVCoBZpGcbtkKA_Ju9TpHx0kdHAWNQ.png)

  

We will be redirected to Facebook for the Developer dashboard

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d91060adcd2fb79c61db0__Z071WE63urQFa-4PxOcXyA7c7-lXuyKLhh5wVZ-aGTCi-kNKQ14CjETolcdXZbxEHVy_atIqzXBSasXWkleeRFJRbm4xze9wooJy77Mi1x5lUc-6HnM-t-j0eLA-nddvJTAW_a_M6Y9NIwDwA.png)

Press button “Create App” for create app in Facebook Developer.

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d9106344322eefaab1e0b_-W32dTa59xiNcpoBIwAexH5S77YXv3ypGPxu4hd2k4BOTUbBH4pHewf76agJjbfCjX5rMqvM4jcda9n4SjvwatEH02d-DWUHU42TIrMPdob1Hyj9pzuXp4acWId99bzvhqOKPlEsjS3l40BI6A.png)

  

Choose “Build Connected Experiences” and the press button “Continue”

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d9106f19c3d4598d01cb3_cmSzbmyUyW80dQeOAAyPskDNiwtmGUl86EolamN7u2Llpcp6wXsEZt7_GUrCSQ4YibPM4P-K60Y0VFOW7QXL_QG6nZp4nhnyZ8Gtsjj1-o_ZzlnKXctB_W98DGEgCWuOui0MpSxxDuYg7ZzEig.png)

  

Fill the App Display Name with what you want to name this app and your email that was previously registered. In this tutorial we use the name “React\_Login”. After that, press the button “Create App”.

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d91069249bd00dddd3dee_zts8LZW3ZcjL66oRmBZ6WrMYcFqIAZWEIZ9V1RrkFQHsK4b5YV-v_Ugy7o6knaMXRjx1xnyH97UmGTRGhxPnQyXdFJElIUI4eC4sEG9TIIKdb7aQKqlqLp_In_Q5QFr8ZzaT718UfOElmioOqQ.png)

After checking the captcha dialog and click submit button, we will be redirected to the Facebook Application Dashboard.

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d9106370911682cc4074f_09CKIjz9VF5Ux3avqyBit2v5pj3IWD3nz4qOM8zG_KhC256xMSKT_ZUKX4XOBnQnvvfS7XWEYEIJpRRBh2KJE6nikQffq88hQtURaMcrw8qgrvsdgHNvGIbJ3Jrl-6m8VgibNe7DASK6SmEUlQ.png)

  

**2\. Create React.js App**
---------------------------

To create a React project we use the command line or CLI. Referring to the https://reactjs.org/docs/create-a-new-react-app.html#gatsby-focus-wrapper, we can create a React project with the command  

> npx create-react-app react-fb\_login  

This command works by downloading the latest React Js template from the repository. Or we can also download the React Js template and place it globally on our computer, so that every time we create a new React project we don't need to download it from the repository. The command line is as follows.  

> npm install -g create-react-app  
> create-react-app react-fb\_login  

Next, go to “ react-fb\_login ” folder and open the project in your IDE or Text Editor. Below is the template structure for our React application

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d9134ad60204fbc70c216_1bdnaSJMsY_mI7fttHj-amuCOVXwjQ7rhyJrgrnF8KcJLlieIQidT_vXd5on9ukMQcMcSspt-kY4MTaCzm6rg_oOr7HifGBH15SX58sKHZOJgd8ncXhRJDW2rqzI0CFlGxcgpiJw.png)

You can also see "package.json" in our React project folder to see what packages are installed by default and the versions of the packages.

    {
      "name": "default_react",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "@testing-library/jest-dom": "^5.11.9",
        "@testing-library/react": "^11.2.5",
        "@testing-library/user-event": "^12.8.0",
        "react": "^17.0.1",
        "react-dom": "^17.0.1",
        "react-scripts": "4.0.3",
        "web-vitals": "^1.1.0"
      },
    

We can run our React project which is the default design template for create-react-app. To run, we only need to call this command in the terminal, where previously we have directed our terminal into our React project folder (react\_fb\_login).  

  

> npm start

  

By default the React app runs on localhost with port 3000.

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d91cead09bdd3d0e8bea6_xfeYmHLYS-sfF7Ei69KRnx7OQL_8IGP_Jm70fLm7OvE7q_KXsNwM8R_wfp_JZJDz0uakA-SaNedlBShMpLKTwHTlkr0fCQTAIfPEsIYDF0HuLIcN40oZK9TlFn7ELTjQu_je3l3tpnaulV2coQ.png)

  

**3\. Install the “ react-facebook-login ” library**
----------------------------------------------------

In this tutorial we will be using the "react-facebook-login" package / modules / library which we will be installed in our React application project. To install this library we just need to use the command below in the terminal from our project directory.  

> npm install react-facebook-login

  

After the install is complete, we will see the “ react-facebook-login ” package has been added to the package.json file.

    {
      "name": "default_react",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "@testing-library/jest-dom": "^5.11.9",
        "@testing-library/react": "^11.2.5",
        "@testing-library/user-event": "^12.8.0",
        "react": "^17.0.1",
        "react-bootstrap": "^1.5.1",
        "react-dom": "^17.0.1",
        "react-facebook-login": "^4.1.1",
        "react-scripts": "4.0.3",
        "web-vitals": "^1.1.0"
      },
    

We need to set up our React app project to running with HTTPS. This is because currently Facebook Login need to use HTTPS. To set this up, we need to replace the script of "start"  in our packagae.json file with the start script below. The packagae.json file is in the directory "react-fb\_login/package.json "

> "start": "HTTPS=true react-scripts start",  

      "scripts": {
        "start": "HTTPS=true react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
      },
    

‍

**4\. Adding Facebook login to our React app**  

-------------------------------------------------

    import React, { useState } from 'react';
    import FacebookLogin from 'react-facebook-login';
    import { Card, Image } from 'react-bootstrap';
    import './App.css';
    
    
    function App() {
    
    
      const [login, setLogin] = useState(false);
      const [data, setData] = useState({});
      const [picture, setPicture] = useState('');
    
    
      const responseFacebook = (response) => {
        console.log(response);
        setData(response);
        setPicture(response.picture.data.url);
        if (response.accessToken) {
          setLogin(true);
        } else {
          setLogin(false);
        }
      }
    
    
      return (
        
          
            
              {!login &&
                
              }
              {login &&
                
              }
            
            {login &&
              
                {data.name}
                
                  {data.email}
                
              
            }
          
        
      );
    }
    
    
    export default App;
    

View [App.js](https://github.com/ghozalihadi/SoftwareEngineeringBlog) in context at [Quod AI](https://quod.ai)

**Line 1-4:** We are calling all the libraries needed to build our React app project, including calling the react-facebook-login, react-bootstrap and react libraries.

**Line 26-39:** We use the FacebookLogin component from the react-facebook-login library to login to Facebook. This library makes it easy for us to configure our React app to log into Facebook. In this component we need to add the appId (appId="<your appId>") that we got from the dashboard at Facebook Developer.

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d9496a26f6817729fa643_Aw_solqDQizvOzknTp_Zeddx8-Dkm3HwVr_o9h7_fQ0p92yq6kxPRlIN-z0F0OV5ERJFUL9RqXRv8d5jKOHJu2h8xbuModB7pcVkd_rZCHffP0KwexXr_VPk1tvfZ0HQoq3SRTq2QEeyyoxybg.png)

  

**Line 36-38:** The FacebookLogin component is a button-like component. The FacebookLogin button will turn into an image component when we have successfully logged in.

**Line 41-47:** Our Facebook profile information will appear in the form of name and email if we have successfully logged in.

**Line 12-21:** This is an arrow function used to capture the response from the FacebookLogin component. In this response we will get an access token and also some profile data from our Facebook.

‍

5. How the FacebookLogin library works
--------------------------------------

To understand how the FacebookLogin library works, we need to take a look at the code we have installed in our project. Open the react-facebook-login folder in the directory "/ node\_modules / react-facebook-login /". Then open the facebook.js file in the directory "/node\_modules/react-facebook-login/dist/facebook.js". Before the FacebookLogin component is rendered, the attributes given to this component will be fetched and processed by FB SDK, especially in the appId we prepared earlier.

    window.FB.init({
      version: 'v' + version,
      appId: appId,
      xfbml: xfbml,
      cookie: cookie
    });
    

View [facebook.js](https://github.com/ghozalihadi/SoftwareEngineeringBlog) in context at [Quod AI](https://quod.ai)

          if (_this.props.isMobile && !disableMobileRedirect) {
            window.location.href = '//www.facebook.com/dialog/oauth?' + (0, _objectToParams2.default)(params);
          } else {
            window.FB.login(_this.checkLoginState, { scope: scope, auth_type: params.auth_type });
          }
    

View [App.js](https://github.com/ghozalihadi/SoftwareEngineeringBlog) in context at [Quod AI](https://quod.ai)

**Line 126**: The login function is executed when we click the login button. Then the response will be caught by the checkLoginState function.

‍

        }, _this.responseApi = function (authResponse) {
          window.FB.api('/me', { locale: _this.props.language, fields: _this.props.fields }, function (me) {
            _extends(me, authResponse);
            _this.props.callback(me);
          });
        }, _this.checkLoginState = function (response) {
          _this.setStateIfMounted({ isProcessing: false });
          if (response.authResponse) {
            _this.responseApi(response.authResponse);
          } else {
            if (_this.props.callback) {
              _this.props.callback({ status: response.status });
            }
          }
    

View [App.js](https://github.com/ghozalihadi/SoftwareEngineeringBlog) in context at [Quod AI](https://quod.ai)

**Line 74:** The authResponse we get will then be processed by the responseApi function.

**Line 69-73** the responseApi data will be returned to the callback function which in our code was previously used to get the profile data response from our Facebook account.

‍

Next step, Open our Facebook Developer dashboard, click on "Settings" in the left navigation, then select "Basic". Continue scrolling down until you find the "+ Add Platform" button.

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d961e6e28797f89d1ab90_U1tZOE9OeSPS7gAxP1gfThwQtSuw95-XzcZ8l08zueIXsjyDMfHhFNCYtsoNg_zHeuWJ6wUn6N8tPOagZmLlw1pL-bHLW0Fpa7UMQKnJRLhqGPIwzXl2-kkz_fX6Q2AWMLsePk0I.png)

Then will be pop up select platform menu. Choose “Website”

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d961ecfa34da9623ed2cf_yM07unKkB0-tMsXFE2GrjqcHyHVthqb8F9xFWisKH3I0HZp1iiTsg33vvM2kHpQiJ5whOgyWV_uAtbue3BWtEqJWnz6tufThoY89iAh5rsxhuw4Oh5QeruccXysMUhOjHwVEnhEn.png)

fill in the " Site URL " container with " [http://127.0.0.1:3000/auth/facebook/callback](http://127.0.0.1:3000/auth/facebook/callback) " and then press the "Save Changes" button.

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d961fc523ef50437e8253_bkmZOewGiqLcZuOa6lq-W7ddOpseuBakoU40IF-ZtBgnb7E0_MZoV3qyvbDf0clDBRv2C6vDlbJgwGTxCysjQpP_9Odg-XoajhYoy74gQGRco58jrAT8Nw3lmmHy3YUEjqlIv36S.png)

  

**6\. Run our React App to login with Facebook**
------------------------------------------------

To run this react app, we use command line like below.  

> npm start  

Go to https://localhost:3000 and you can see the browser displays a button to Login With Facebook as below.

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d961f3d647985ef8c41f0_ktbYkSvWm1TMozrECZtaOFyHq429joyqK9DDc76HN0SUl4UvMADcjMfvAR7la2ZfHuFEdZYFLFZbBXPyiWDAvAkVvKkwr_K7o3TzaXIjbOCTAzBXLOniGeI2O5rhzd2YUeXFw2OeX-D0CjtcGQ.png)

‍

Click the \`Login with Facebook\` button then it will be a Facebook login dialog pop up.

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d961f6e2879db66d1ab91_fH4QnDxShEsh6kNQdfAlTE-JPZi9Hi8nuiuL4gEk1VoQDnAaKRsI1DsQ_y1BOGBgCjh2reRbhARFjqhV3thk7kOjL0UKVCpwfTKYweH9bSf1G0FkXUqpeUIH6LRzd1SEbobEFybDCZ-2E0GABA.png)

  

Enter your email address or phone number and password. Then press button “Log in”. It will be a Facebook login dialog pop up again. Press button “Continue as "your\_name"” and it will be back to the previous page with this data.

  

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d961f1ebcd7a6e627ed57_Q3lOGzLxUHlAOyas3dzXE4K4OM8ePmjy9ME564J6hvr5Ddq8qXXrz6KJKOk--VHW4BkmvaS1V8oyFaPtHXXFwDnf1uecl16qIDOzQYCmu_ouS1qMvGgaW7wIKjWJY5Aed-Ihop6djqV-Iygo3Q.png)

  

Congratulations, you have successfully integrated reactions with Facebook using the Facebook Login API. In our browser, it displays the profile picture and name of our Facebook account.

‍  

![](https://uploads-ssl.webflow.com/5e733294d7b5a568ffa60a00/605d961fcdf942ddc300ca53_2n15m5sggS4ymEE1O3nvZNIck--QBNW9x8_v1XGJ4-z_xXMbEhMm7nIegbBa2VwPN07vO3yuJAEjAR3cHJ5jLZNB-UsedZCW1MCuVdR_4gtpNSq1sXFmsVqGUAmkEywlO16zg-FzHAwjtLtSEA.png)

  

You can see the full code on our GitHub repository: [https://github.com/QuodAI/tutorial-react-facebook-api-login](https://github.com/QuodAI/tutorial-react-facebook-api-login)

Quod AI is code search and navigation on steroids. We turn code into documentation that developers actually use. Do follow us on Twitter [@quod\_ai](https://twitter.com/quod_ai) for updates on our product and DEVs community content.

Check our app at: [beta.quod.ai](https://beta.quod.ai/)