React.js Tutorial: Facebook Login Example

by Didin J. on Mar 15, 2020 React.js Tutorial: Facebook Login Example

A comprehensive step by step React.js tutorial on adding Facebook login to the React.js application with a full working example

Nowadays, Facebook login is part of the authentication mechanism beside Google login on web applications or mobile apps. Actually, using the Facebook log in can be done in just the Front-end side because it uses Facebook SDK for Javascript. Luckily, there is a react-facebook-login module that we will use for this React.js FB login.

This tutorial divided into several steps:

The following tools, frameworks, and modules are required for this tutorial:

  1. Node.js (with NPM or Yarn)
  2. React.js (min. version 16.8)
  3. react-facebook-login
  4. Terminal or Node Command Line
  5. IDE or Text Editor (We are using Visual Studio Code)

Before going to the main steps, make sure, you have installed Node.js and can run NPM or Yarn. To check them, type these commands.

node -v
npm -v
yarn -v


Step #1: Set up a Facebook App

To setup, a Facebook App and get an App ID/Secret, go to Facebook Developers Apps https://developers.facebook.com/apps/. Login with your Facebook developer's account or credentials. 

React.js Tutorial: Facebook Login Example - Developers Facebook

Click the `+ Add a New App` button or MyApps -> Create App button. 

React.js Tutorial: Facebook Login Example - New App

Enter the display name (we use `MyReactApp` name) then click the `Create App ID` button. Make sure to use the valid name allowed by Facebook Developers.

React.js Tutorial: Facebook Login Example - New App ID

After checking the captcha dialog and click submit button, now, you can see App ID and Secret, write it to your notepad.

React.js Tutorial: Facebook Login Example - App Dashboard

Click the Settings menu on the left menu then click Basic. Scroll down then click the `+ Add Platform` button then choose the website. Fill site URL with the callback URL for OAuth authentication callback URL, we are using this callback URL `http://127.0.0.1:1337/auth/facebook/callback`.

React.js Tutorial: Facebook Login Example - Site URL

Click the `Save Changes` button and now the Facebook apps are ready to use with your React.js application.


Step #2: Install create-react-app and Create React.js App

To create a new React.js application, we will use the create-react-app tool. The create-react-app is a tool to create a React.js app from the command line or CLI. So you don’t need to install or configure tools like Webpack or Babel because they are preconfigured and hidden so that you can focus on the code. Type this command to install it.

sudo npm install -g create-react-app

Now, we can create a new React.js app using that tool.

create-react-app react-fblogin

This command will create a new React app with the name `react-fblogin` and this process can take minutes because all dependencies and modules also installing automatically. Next, go to the newly created app folder.

cd ./react-fblogin

Open the project in your IDE or text editor and see the content of package.json.

  "dependencies": {
    ...
    "react": "^16.13.0",
    "react-dom": "^16.13.0",
    "react-scripts": "3.4.0"
  },

That React version is the version that already uses React Hooks as default. Now, `src/App.js` doesn't use class anymore. For sanitation, run this React app for the first time by type this command.

yarn start

And here' we go the latest React.js application that uses React Hooks with the same initial home page.

React.js Tutorial: Facebook Login Example - React Home


Step #3: Install and Configure react-facebook-login

We will use the React Facebook Login module/library found on the NPMJS with the name react-facebook-login. To install it, type this command.

yarn add react-facebook-login

Because now the Facebook Login force to use HTTPS only, we need to modify this React.js app to run with HTTPS. Open and edit `package.json` then modify "start" in the "scripts" object.

  "scripts": {
    "start": "HTTPS=true react-scripts start",
    ...
  },


Step #4: Display Sign In With Facebook Button and Basic User Profile

Now, we will display the sign in with the Facebook button and show the basic user profile after login successful. For UI we will use the React Bootstrap module. Type this command to install it.

yarn add react-bootstrap bootstrap

To use Bootstrap CSS from CDN, open and edit `public/index.html` then add this <link> before the closing of </head>.

    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
      integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
      crossorigin="anonymous"
    />

Next, open and edit `src/App.js` then replace all React.js codes with this.

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 (
    <div class="container">
      <Card style={{ width: '600px' }}>
        <Card.Header>
          { !login && 
            <FacebookLogin
              appId="562118384400275"
              autoLoad={true}
              fields="name,email,picture"
              scope="public_profile,user_friends"
              callback={responseFacebook}
              icon="fa-facebook" />
          }
          { login &&
            <Image src={picture} roundedCircle />
          }
        </Card.Header>
        { login &&
          <Card.Body>
            <Card.Title>{data.name}</Card.Title>
            <Card.Text>
              {data.email}
            </Card.Text>
          </Card.Body>
        }
      </Card>
    </div>
  );
}

export default App;


Step #5: Run and Test React.js Login App

To run this React.js Facebook Login app, simply type this command.

yarn start

The browser will automatically open and you will see this page if there's no Facebook login session.

React.js Tutorial: Facebook Login Example - Demo 1

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

React.js Tutorial: Facebook Login Example - Demo 2

Fill the username and password that use as a Facebook Developers account because in previous Facebook App setup we use development mode. Then click the login button.

React.js Tutorial: Facebook Login Example - Demo 3

Click the Continue as "your_name" button and it will be back to the previous page with this data.

React.js Tutorial: Facebook Login Example - Demo 4

That it's, React.js Tutorial: Facebook Login Example. You can find the full source code from our GitHub.

That just the basic. If you need more deep learning about MERN Stack, React.js or React Native you can take the following cheap course:

Thanks!

Loading…