Login With Facebook Using ReactJS

Introduction

 
In this article, we will learn the step-by-step process of allowing users to log in to an application with Facebook using ReactJS. Logging in with Facebook makes it safe and easy for users to use applications. When a user clicks on the Login with Facebook button, the user is navigated Facebook to give the app permission. In response, the user receives a token key and other personal details.
 
Prerequisites
Topics Covered in this Article,
  • Create a ReactJS Project
  • Install rreact-facebook-login React plugin
  • Install Axios and Bootstrap
  • Add React Router
  • Install Bootstrap and React strap
  • Create a Google App and get client Id
  • Create a database and table
  • Create a Web API Project
Create a ReactJS project by using the following command
  1. npx create-react-app sociallogin   
 Open the newly-created project in Visual Studio code and install react-google-login React plugin using the following command
  1. npm install react-facebook-login --save  
 Now install Bootstrap in this project by using the following command.
  1. npm install --save bootstrap      
Now, open the index.js file and add import Bootstrap. 
  1. import 'bootstrap/dist/css/bootstrap.min.css';   
Now install the Axios library by using the following command. Learn more about Axios 
  1. npm install --save axios      

Create a Facebook App and Get App Id

 
Go to Facebook developer page and create a new App, 
 
Login With Facebook Using ReactJS
 
Click on create App ID
 
Login With Facebook Using ReactJS
 
Click on Facebook login setup
 
Login With Facebook Using ReactJS
 
Click on Web
 
Login With Facebook Using ReactJS
 
Enter Site url and click on save, now go to setting, and copy app id
 
Now, in Visual Studio code, go to src folder and create a new folder and inside this folder add 2 new components
  1. Loginbyfacebook.js
  2. Dashboard.js

Add Routing in ReactJS

 
Install react-router-dom package by using the following command
  1. npm install react-router-dom --save   
Open app.js file and imports of Router and Route (react-router-dom) and 2 components.
  1. import Logintbygoogle from './Logintbygoogle'      
  2. import Dashboard from "./Dashboard";      
  3. import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';  
Add the following code in app.js file,
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import Logintbyfacebook from './Logintbyfacebook'  
  5. import Dashboard from "./Dashboard";  
  6. import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';   
  7. function App() {  
  8.   return (  
  9.     <>  
  10.    <div className="App">    
  11.      <Router>      
  12.       <div className="container">     
  13.         <Switch>      
  14.           <Route exact path='/' component={Logintbyfacebook} />      
  15.           <Route path='/Dashboard' component={Dashboard} />       
  16.         </Switch>      
  17.       </div>      
  18.     </Router>      
  19.     </div>    
  20.    </>  
  21.   );  
  22. }  
  23.   
  24. export default App;  
Now, open the Loginbyfacebook.js file and add the following code.
  1. import React, { Component } from 'react'  
  2. import FacebookLogin from 'react-facebook-login';  
  3. import axios from 'axios'  
  4. export class Logintbyfacebook extends Component {  
  5.         constructor(props) {  
  6.                 super(props);  
  7.                 this.state = {  
  8.               
  9.                 };  
  10.               }  
  11.               signup(res) {  
  12.                 const responseFacebook = {  
  13.                   Name: res.name,  
  14.                   email: res.email,  
  15.                   token: res.accessToken,  
  16.                   Image: res.picture.data.url,  
  17.                   ProviderId: 'Facebook'  
  18.               
  19.                 }  
  20.           
  21.                 debugger;  
  22.                 axios.post('http://localhost:60200/Api/Login/SocialmediaData', responseFacebook)  
  23.                   .then((result) => {  
  24.                     let responseJson = result;  
  25.                     console.log(result.data.name);  
  26.                     alert("data");  
  27.                     sessionStorage.setItem("userData", JSON.stringify(result));  
  28.                     this.props.history.push('/Dashboard')  
  29.                   });  
  30.               };  
  31.                  render() {  
  32.                 const responseFacebook = (response) => {  
  33.                         console.log(response);  
  34.                         var res = response.profileObj;  
  35.                         console.log(res);  
  36.                         debugger;  
  37.                         this.signup(response);  
  38.                       }  
  39.                 return (  
  40.                         <div className="App">  
  41.                         <div className="row">  
  42.                           <div className="col-sm-12 btn btn-info">  
  43.                             Login With Facebook Using ReactJS  
  44.                             </div>  
  45.                         </div>  
  46.                         <div className="row">  
  47.                           <div style={{ 'paddingTop'"20px" }} className="col-sm-12">  
  48.                             <div className="col-sm-4"></div>  
  49.                             <div className="col-sm-4">  
  50.                             <FacebookLogin buttonStyle={{padding:"6px"}}  
  51.                              appId="682908192243627"  
  52.                              autoLoad={false}  
  53.                              fields="name,email,picture"  
  54.                              callback={responseFacebook}/>  
  55.                             </div>  
  56.                             <div className="col-sm-4"></div>  
  57.                           </div>  
  58.                         </div>  
  59.                       </div>  
  60.                 )  
  61.         }  
  62. }  
  63.   
  64. export default Logintbyfacebook  
 Now, open the Dashboard .js file and add the following code.
  1. import React, { Component } from 'react'  
  2.   
  3. export class Dashboard extends Component {  
  4.         constructor(props){  
  5.                 super(props);  
  6.                 this.state = {  
  7.                 name:'',  
  8.                 };  
  9.                }  
  10.   componentDidMount() {  
  11.         const data = JSON.parse(sessionStorage.getItem('userData'));  
  12.         let data1=data;  
  13.         console.log(data1.data.Name);  
  14.       
  15.          console.log(data1.Name);  
  16.          this.setState({name: data1.data.Name})  
  17.       }  
  18.         render() {  
  19.                 return (  
  20.                         <div className="container">     
  21.                          <div className="row">    
  22.                                   <div className="col-sm-12 btn btn-info">    
  23.                                  Welcome to Dashboard  
  24.                          </div>    
  25.                          </div>  
  26.                          <div className="row">  
  27.                          <div className="col-sm-3"> Welcome  :{this.state.name} </div>  
  28.                          <div className="col-sm-9"></div>  
  29.                          {/* <div className="col-sm-4"></div> */}  
  30.                          </div>  
  31.                         </div>  
  32.                 )  
  33.         }  
  34. }  
  35.   
  36. export default Dashboard  

Create a table in the Database

 
Open SQL Server Management Studio, create a database named "Demotest," and in this database, create a table. Give that table a name like "sociallogin".
  1. CREATE TABLE [dbo].[Socaillogin](      
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,      
  3.     [Name] [varchar](50) NULL,      
  4.     [Email] [varchar](50) NULL,      
  5.     [ProviderName] [varchar](50) NULL,      
  6.     [Image] [varchar](650) NULL,      
  7.     [Token] [nvarchar](650) NULL,      
  8.  CONSTRAINT [PK_Socaillogin] PRIMARY KEY CLUSTERED       
  9. (      
  10.     [Id] ASC      
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]      
  12. ) ON [PRIMARY]      
  13. GO       

Create a Web API Project

 
Open Visual Studio and create a new project.
 
Login With Facebook Using ReactJS
 
Change the name
 
Login With Facebook Using ReactJS
 
Select Web API as its template.
 
Login With Facebook Using ReactJS
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
Login With Facebook Using ReactJS
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
Login With Facebook Using ReactJS
 
Select the EF Designer from the database and click the "Next" button.
 
Login With Facebook Using ReactJS
 
Add the connection properties and select database name on the next page and click OK.
 
Login With Facebook Using ReactJS
 
Check the Table checkbox. The internal options will be selected by default. Now, click the "Finish" button.
 
Login With Facebook Using ReactJS
 
Our data model is created successfully now.
 
Now, Right-click on the model folder and add two classes - Userdetails and Response. Now, paste the following code in these classes.
 
Userdetails class 
  1. public class Userdetails      
  2.     {      
  3.         public int Id { getset; }      
  4.         public string Name { getset; }      
  5.         public string Email { getset; }      
  6.         public string ProviderName { getset; }      
  7.         public string Image { getset; }      
  8.         public string Token { getset; }      
  9.     }      
 Response Class
  1. public class Response          
  2.    {          
  3.        public string Status { setget; }          
  4.        public string Message { setget; }          
  5.    }      
Right-click on the Controllers folder and add a new controller. Name it as "Login controller" and add the following namespace. 
  1. using LoginWithSocialMedio.Models;  
 Create a method in this controller to save data. Add the following code in this controller.
  1. using System;      
  2. using System.Collections.Generic;      
  3. using System.Linq;      
  4. using System.Net;      
  5. using System.Net.Http;      
  6. using System.Web.Http;      
  7. using LoginWithSocialMedio.Models;      
  8.       
  9. namespace LoginWithSocialMedio.Controllers      
  10. {      
  11.     [RoutePrefix("Api/Login")]      
  12.     public class LoginController : ApiController      
  13.     {      
  14.         [Route("SocialmediaData")]      
  15.         [HttpPost]      
  16.         public object SocialmediaData(Userdetails user)      
  17.         {      
  18.             try      
  19.             {      
  20.                 DemoTestEntities DB = new DemoTestEntities();      
  21.                 Socaillogin Social = new Socaillogin();      
  22.                 if (Social.Id == 0)      
  23.                 {      
  24.                     Social.Name = user.Name;      
  25.                     Social.Email = user.Email;      
  26.                     Social.ProviderName = user.ProviderName;      
  27.                     Social.Image = user.Image;      
  28.                     Social.Token = user.Token;      
  29.                     var res = DB.Socaillogins.Add(Social);      
  30.                     DB.SaveChanges();      
  31.                     return res;      
  32.                 }      
  33.             }      
  34.             catch (Exception)      
  35.             {      
  36.                 throw;      
  37.             }      
  38.             return new Response      
  39.             { Status = "Error", Message = "Data." };      
  40.         }      
  41.     }      
  42. }    
Now, let's enable Cors. Go to Tools, open NuGet Package Manager, search for Cors and install the Microsoft.Asp.Net.WebApi.Cors package. Open Webapiconfig.cs, and add the following lines.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");      
  2. config.EnableCors(cors);     
Now to go Visual Studio code and run the project 
 
Login With Facebook Using ReactJS
Click on 'login with Facebook' button,
 
Login With Facebook Using ReactJS
 
Enter e-mail and password.
 
Login With Facebook Using ReactJS
Now if login is successful, then it redirects to the dashboard page.
 

Summary

 
In this article, we discussed the process of logging in with Facebook using React and Web API.