DEV Community

Cover image for Facebook Authentication Login on React App
ronakvsoni
ronakvsoni

Posted on

Facebook Authentication Login on React App

A comprehensive step by step React.js tutorial on adding Facebook login to the React.js application with a fully 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 blog divided into several steps:

  • Step #1: Set up a Facebook App
  • Step #2: Install create-react-app and Create React.js App
  • Step #3: Install and Configure react-facebook-login
  • Step #4: Display Sign In With Facebook Button and Basic User Profile
  • Step #5: Run and Test React.js Login App

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
  3. IDE or Text Editor (I am 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.Alt TextClick the + Add a New App button or MyApps -> Create App button.Alt TextEnter 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.Alt TextAfter checking the captcha dialog and click submit button, now, you can see App ID and Secret, write it to your notepad.Alt TextClick 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.Alt TextClick 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

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

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 before the closing of .

    <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.Alt TextClick the Login with Facebook button then it will be a Facebook login dialog pop up.

-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.

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

Thank you for reading!!

Sources

https://www.npmjs.com/package/react-facebook-login
https://www.youtube.com/watch?v=tr0nttQtwZg&feature=emb_title

Top comments (0)