Step by step guide to adding Google login to your React app

how-to-adding-Google-login-to-your-React-app

To add Google login functionality to your React app, you can use the ‘react-google-login’ library. Here’s a step-by-step guide:

Step 1: Create a Google Project and Configure OAuth

  • Go to the Google Cloud Console.
  • Create a new project or select an existing one.
  • In the left navigation panel, click on “APIs & Services” > “Credentials.”
  • Click on “Create Credentials” and select “OAuth client ID.”
  • Choose “Web application” as the application type.
  • Set the authorized JavaScript origins and redirect URIs. For development, you can set http://localhost:3000 as the redirect URI.
  • After creating the OAuth client ID, note down the client ID.

Step 2: Create a React App

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

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

Step 3: Install react-google-login

Install the ‘react-google-login’ library:

npm install react-google-login

Step 4: Create a GoogleLogin Component

Create a new component named ‘GoogleLoginButton.js’:

// src/components/GoogleLoginButton.js

import React from 'react';
import { GoogleLogin } from 'react-google-login';

const GoogleLoginButton = ({ onSuccess, onFailure }) => {
  const clientId = 'YOUR_GOOGLE_CLIENT_ID'; // Replace with your actual Google Client ID

  return (
    
  );
};

export default GoogleLoginButton;

Replace ‘YOUR_GOOGLE_CLIENT_ID’ with the actual client ID you obtained from the Google Cloud Console.

Step 5: Use the GoogleLogin Component in App.js

Update your src/App.js file to use the GoogleLoginButton component:

// src/App.js

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

function App() {
  const onGoogleLoginSuccess = (response) => {
    console.log('Google login success:', response);
    // Handle the successful login, e.g., set user state, store tokens, etc.
  };

  const onGoogleLoginFailure = (error) => {
    console.error('Google login failure:', error);
    // Handle the login failure, e.g., show an error message
  };

  return (
    

React Google 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 Google” button, it should trigger the Google login process.

Remember to replace ‘YOUR_GOOGLE_CLIENT_ID’ with your actual Google Client ID. Additionally, handle the success and failure callbacks according to your application’s requirements.

Related Posts