Besides of login using email and password, social media login is very popular these days. If you want to grow user base fast, it’s hard to imagine that you don’t want social media login. In this tutorial, I will help you to implement a Facebook login flow into your React application.

There are 2 methods to implement social media login

  • Use social media’s Javascript SDK. It works well for any Single Page Application like React, Angular, VueJS, etc. The SDK does the most hard work and you only have to call login method and handle the callback. This method only works for Facebook and Google since only them support Javascript SDK.
  • Use social media’s REST API. Almost every social media website (include Facebook, Google, Twitter, Github, LinkedIn etc..) support this method. But they are NO Single Page Application friendly since usually it requires our application to redirect to social media login page, thus breaks application state (unless you have saved) so they are more suitable when your website is rendered by server instead user’s browser. We could avoid this problem using a popup, but let’s discuss about this method in another post.

Before you start, you can grab the source code of this tutorial at here: https://github.com/davidtran/react-facebook-javascript-sdk-login

Let’s start

Step 1:

In order to integrate social media login of any platform, you have to create an app on that platform. For Facebook, you have to go to https://developers.facebook.com/apps/ and click Add a New App from My app dropdown. After your app is created, click on your app and go to Products > Facebook Login > Settings to set Redirect URL.

Step 2:

This is the code that you need to copy into index.html to enable Facebook login. You should insert it right after <body> tag. You need to replace your-app-id by your app ID.

<script>
    window.fbAsyncInit = function () {
      FB.init({
        appId: '1813842465324998',
        autoLogAppEvents: true,
        xfbml: true,
        version: 'v2.11'
      });

      // Broadcast an event when FB object is ready
      var fbInitEvent = new Event('FBObjectReady');
      document.dispatchEvent(fbInitEvent);
    };

    (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'));
  </script>

Right after the line FB.init. We create a new event object “FBObjectReady” and broadcast that event object. This event let us know when FB object is ready which we will use in our FacebookLoginButton component.

Now let’s implement our Facebook login button.

Step 3 – Implement Facebook Login Button component

We create this component because we want to reuse it anywhere in our application. After created this component, we can place in the login form or in the top menu or anywhere that you want to have Facebook login feature.

Now create a new file FacebookLoginButton and paste the following code:

import React, { Component } from 'react';

export default class FacebookLogin extends Component {

  componentDidMount() {
    document.addEventListener('FBObjectReady', this.initializeFacebookLogin);
  }

  componentWillUnmount() {
    document.removeEventListener('FBObjectReady', this.initializeFacebookLogin);
  }

  /**
   * Init FB object and check Facebook Login status
   */
  initializeFacebookLogin = () => {
    this.FB = window.FB;
    this.checkLoginStatus();
  }

  /**
   * Check login status
   */
  checkLoginStatus = () => {
    this.FB.getLoginStatus(this.facebookLoginHandler);
  }

  /**
   * Check login status and call login api is user is not logged in
   */
  facebookLogin = () => {
    if (!this.FB) return;

    this.FB.getLoginStatus(response => {
      if (response.status === 'connected') {
        this.facebookLoginHandler(response);
      } else {
        this.FB.login(this.facebookLoginHandler, {scope: 'public_profile'});
      }
    }, );
  }

  /**
   * Handle login response
   */
  facebookLoginHandler = response => {
    if (response.status === 'connected') {
      this.FB.api('/me', userData => {
        let result = {
          ...response,
          user: userData
        };
        this.props.onLogin(true, result);
      });
    } else {
      this.props.onLogin(false);
    }
  }

  render() {
    let {children} = this.props;
    return (
      <div onClick={this.facebookLogin}>
        {children}
      </div>
    );
  }
}

Let’s me explain every methods in this component.

First of all, when componentDidMount is called, we add an event listener to listen to event FBObjectReady and initialize our component. We need to do it because if we call any methods in FB object and FB is undefined, our app will throw the error. When our component is unmounted at componentWillUnmount method, we call document.removeEventListener to clean up our listener and prevent memory leak.

Now at the method initializeFacebookLogin, we assign FB object as a property of our component and call a method to check login status. After that, the method facebookLoginHandler will check login status. If login success, it get user details and call onLogin callback which is props that is passed from parent component.

In the render method, we wrap the children by a div and set the handler for onClick event.

Step 4 – Integrate Facebook login button into our app

Here is the source code of App.js. I created this app using create-react-app.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import FacebookLoginButton from './FacebookLoginButton';

class App extends Component {

  state = {
    username: null
  };

  onFacebookLogin = (loginStatus, resultObject) => {
    if (loginStatus === true) {
      this.setState({
        username: resultObject.user.name
      });
    } else {
      alert('Facebook login error');
    }
  }

  render() {
    const { username } = this.state;

    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">React Social Media Login</h1>
        </header>

        <div className="App-intro">
          { !username &&
            <div>
              <p>Click on one of any button below to login</p>
              <FacebookLoginButton onLogin={this.onFacebookLogin}>
                <button>Facebook</button>
              </FacebookLoginButton>
            </div>
          }
          {username &&
            <p>Welcome back, {username}</p>
          }
        </div>
      </div>
    );
  }
}

export default App;

In App.js, we wrap Facebook button by component FacebookLoginButton. When user clicks on this button, it will authenticate user account in Facebook and call onFacebookLogin after finished. If login success, it stores username in the state and render welcome message.

Thanks for reading this tutorial.

If you have any concern, feel free to send me a message or leave a comment.