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. 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. signup(res) {
  11. const responseFacebook = {
  12. Name: res.name,
  13. email: res.email,
  14. token: res.accessToken,
  15. Image: res.picture.data.url,
  16. ProviderId: 'Facebook'
  17. }
  18. debugger;
  19. axios.post('http://localhost:60200/Api/Login/SocialmediaData', responseFacebook)
  20. .then((result) => {
  21. let responseJson = result;
  22. console.log(result.data.name);
  23. alert("data");
  24. sessionStorage.setItem("userData", JSON.stringify(result));
  25. this.props.history.push('/Dashboard')
  26. });
  27. };
  28. render() {
  29. const responseFacebook = (response) => {
  30. console.log(response);
  31. var res = response.profileObj;
  32. console.log(res);
  33. debugger;
  34. this.signup(response);
  35. }
  36. return (
  37. <div className="App">
  38. <div className="row">
  39. <div className="col-sm-12 btn btn-info">
  40. Login With Facebook Using ReactJS
  41. </div>
  42. </div>
  43. <div className="row">
  44. <div style={{ 'paddingTop': "20px" }} className="col-sm-12">
  45. <div className="col-sm-4"></div>
  46. <div className="col-sm-4">
  47. <FacebookLogin buttonStyle={{padding:"6px"}}
  48. appId="682908192243627"
  49. autoLoad={false}
  50. fields="name,email,picture"
  51. callback={responseFacebook}/>
  52. </div>
  53. <div className="col-sm-4"></div>
  54. </div>
  55. </div>
  56. </div>
  57. )
  58. }
  59. }
  60. export default Logintbyfacebook
Now, open the Dashboard .js file and add the following code.
  1. import React, { Component } from 'react'
  2. export class Dashboard extends Component {
  3. constructor(props){
  4. super(props);
  5. this.state = {
  6. name:'',
  7. };
  8. }
  9. componentDidMount() {
  10. const data = JSON.parse(sessionStorage.getItem('userData'));
  11. let data1=data;
  12. console.log(data1.data.Name);
  13. console.log(data1.Name);
  14. this.setState({name: data1.data.Name})
  15. }
  16. render() {
  17. return (
  18. <div className="container">
  19. <div className="row">
  20. <div className="col-sm-12 btn btn-info">
  21. Welcome to Dashboard
  22. </div>
  23. </div>
  24. <div className="row">
  25. <div className="col-sm-3"> Welcome :{this.state.name} </div>
  26. <div className="col-sm-9"></div>
  27. {/* <div className="col-sm-4"></div> */}
  28. </div>
  29. </div>
  30. )
  31. }
  32. }
  33. 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 { get; set; }
  4. public string Name { get; set; }
  5. public string Email { get; set; }
  6. public string ProviderName { get; set; }
  7. public string Image { get; set; }
  8. public string Token { get; set; }
  9. }
Response Class
  1. public class Response
  2. {
  3. public string Status { set; get; }
  4. public string Message { set; get; }
  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. namespace LoginWithSocialMedio.Controllers
  9. {
  10. [RoutePrefix("Api/Login")]
  11. public class LoginController : ApiController
  12. {
  13. [Route("SocialmediaData")]
  14. [HttpPost]
  15. public object SocialmediaData(Userdetails user)
  16. {
  17. try
  18. {
  19. DemoTestEntities DB = new DemoTestEntities();
  20. Socaillogin Social = new Socaillogin();
  21. if (Social.Id == 0)
  22. {
  23. Social.Name = user.Name;
  24. Social.Email = user.Email;
  25. Social.ProviderName = user.ProviderName;
  26. Social.Image = user.Image;
  27. Social.Token = user.Token;
  28. var res = DB.Socaillogins.Add(Social);
  29. DB.SaveChanges();
  30. return res;
  31. }
  32. }
  33. catch (Exception)
  34. {
  35. throw;
  36. }
  37. return new Response
  38. { Status = "Error", Message = "Data." };
  39. }
  40. }
  41. }
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.