How to adding facebook login to your React JS project

adding-facebook-login-to-your-React-JS-project

To add Facebook login functionality to your React project, you can use the react-facebook-login library. Here’s a step-by-step guide:

Step 1: Create a Facebook App and Configure OAuth

  • Go to the Facebook Developers.
  • Create a new app or select an existing one.
  • In the app dashboard, navigate to “Settings” > “Basic.”
  • Note down the App ID and App Secret.
  • Under “Add a Product,” choose “Facebook Login” and configure the OAuth settings. Add http://localhost:3000 to the Valid OAuth Redirect URIs for development.
  • Save the changes.

Step 2: Create a React Project

If you haven’t created a React project yet, use Create React App:

npx create-react-app my-facebook-login-app
cd my-facebook-login-app

Step 3: Install react-facebook-login

Install the ‘react-facebook-login’ library:

npm install react-facebook-login

Step 4: Create a FacebookLogin Component

Create a new component named ‘FacebookLoginButton.js’:

// src/components/FacebookLoginButton.js

import React from 'react';
import FacebookLogin from 'react-facebook-login';

const FacebookLoginButton = ({ onLoginSuccess, onLoginFailure }) => {
  const appId = 'YOUR_FACEBOOK_APP_ID'; // Replace with your actual Facebook App ID

  const responseFacebook = (response) => {
    if (response.accessToken) {
      console.log('Facebook login success:', response);
      // Handle the successful login, e.g., set user state, store tokens, etc.
      onLoginSuccess(response);
    } else {
      console.error('Facebook login failure:', response);
      // Handle the login failure, e.g., show an error message
      onLoginFailure(response);
    }
  };

  return (
    
  );
};

export default FacebookLoginButton;

Replace ‘YOUR_FACEBOOK_APP_ID’ with the actual App ID you obtained from the Facebook Developers portal.

Step 5: Use the FacebookLoginButton Component in App.js

Update your ‘src/App.js’ file to use the ‘FacebookLoginButton’ component:

// src/App.js

import React from 'react';
import FacebookLoginButton from './components/FacebookLoginButton';

function App() {
  const onFacebookLoginSuccess = (response) => {
    // Handle the successful login, e.g., set user state, store tokens, etc.
  };

  const onFacebookLoginFailure = (response) => {
    // Handle the login failure, e.g., show an error message
  };

  return (
    

React Facebook Login

); } export default App;

Step 6: Run Your React App

Save your files and run:

npm start

Visit http://localhost:3000 in your browser. When you click the “Login with Facebook” button, it should trigger the Facebook login process.

Remember to replace ‘YOUR_FACEBOOK_APP_ID’ with your actual Facebook App ID. Additionally, handle the success and failure callbacks according to your application’s requirements.

Related Posts