Clue Mediator

Login with Google using React

📅December 11, 2020

Today we’ll show you how to implement the login with google using React. In this article, we will add the Google Sign-In and Sign-Out button to manage the authentication process with google account.

Here, we have to use the OAuth Client Id with npm package. Will also show you the process to generate the OAuth Client Id.

Steps to Implement Login with Google using React

  1. Create Google App and generate OAuth Client Id
  2. Create react application
  3. Install npm dependency
  4. Authenticate component with Google using Auth0
  5. Output

1. Create Google App and generate OAuth Client Id

First of all, we have to generate an OAuth Client Id for use with requests from a browser.

Follow the steps to get Client Id.

Step 1: Go to the Google API Console and click on Credentials.

Google API Console - Clue Mediator

Google API Console - Clue Mediator

Step 2: Now click on the Create Credentials and select OAuth client ID.

Create Credentials - Clue Mediator

Create Credentials - Clue Mediator

Step 3: Select the Web application from the dropdown of the Application type.

Application Type - Clue Mediator

Application Type - Clue Mediator

Step 4: Now enter the name of the OAuth client and add the project URL. At last click on the Create button to create an OAuth client.

Create OAuth Client ID - Clue Mediator

Create OAuth Client ID - Clue Mediator

Step 5: After successful creation, you will get the Client ID and Client Secret for the application but we will only use the Client ID in the React App.

OAuth Client ID - Clue Mediator

OAuth Client ID - Clue Mediator

2. Create react application

Let’s use the `create-react-app` package to create a react app. Run the following command to set up the react project.

npx create-react-app login-with-google-react

3. Install npm dependency

We will use the react-google-login to implement the Google Sign-In and Sign-Out button. Run the following command to install the package in the react app.

npm i react-google-login

4. Authenticate component with Google using Auth0

In this example, we’ll use the state variable to handle the authentication. In the live project, you have to use the access token for authentication.

Let’s import the `GoogleLogin` and `GoogleLogout` button from the `react-google-login` package. Check the following code and pass the Google App OAuth Client ID through variable.

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

const clientId = "<google_oauth_client_id>";

function App() {

  const [loading, setLoading] = useState('Loading...');
  const [user, setUser] = useState(null);

  // ...
  // write a method to handle events
  // ...

  return (
    <div>
      <h3>Login with Google using React - <a href="https://www.cluemediator.com/" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3>
      {user ? <div>
        <div class="name">Welcome {user.name}!</div>
        <googlelogout clientid={clientId} onlogoutsuccess={handleLogoutSuccess} onfailure={handleLogoutFailure}>
        <pre>{JSON.stringify(user, null, 2)}</pre>
      </googlelogout></div> :
        <googlelogin clientid={clientId} buttontext={loading} onsuccess={handleLoginSuccess} onfailure={handleLoginFailure} onrequest={handleRequest} onautoloadfinished={handleAutoLoadFinished} issignedin={true}>}
    </googlelogin></div>
  );
}

export default App;
</google_oauth_client_id>

In the above code, we have also printed the logged in user information in the `pre` tag. To validate the user on page load, we have set the `isSignedIn` props to the `true`. Check out the more props of the package.

Let’s write a method to handle several events. Check the below code.

App.js

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

const clientId = "<google_oauth_client_id>";

function App() {

  const [loading, setLoading] = useState('Loading...');
  const [user, setUser] = useState(null);

  const handleLoginSuccess = (response) => {
    console.log("Login Success ", response);
    setUser(response.profileObj);
    setLoading();
  }

  const handleLoginFailure = error => {
    console.log("Login Failure ", error);
    setLoading();
  }

  const handleLogoutSuccess = (response) => {
    console.log("Logout Success ", response);
    setUser(null);
  }

  const handleLogoutFailure = error => {
    console.log("Logout Failure ", error);
  }

  const handleRequest = () => {
    setLoading("Loading...");
  }

  const handleAutoLoadFinished = () => {
    setLoading();
  }

  return (
    <div>
      <h3>Login with Google using React - <a href="https://www.cluemediator.com/" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3>
      {user ? <div>
        <div class="name">Welcome {user.name}!</div>
        <googlelogout clientid={clientId} onlogoutsuccess={handleLogoutSuccess} onfailure={handleLogoutFailure}>
        <pre>{JSON.stringify(user, null, 2)}</pre>
      </googlelogout></div> :
        <googlelogin clientid={clientId} buttontext={loading} onsuccess={handleLoginSuccess} onfailure={handleLoginFailure} onrequest={handleRequest} onautoloadfinished={handleAutoLoadFinished} issignedin={true}>}
    </googlelogin></div>
  );
}

export default App;
</google_oauth_client_id>

5. Output

Run the application and check the output in the browser.

Output - Login with Google using React - Clue Mediator

Output - Login with Google using React - Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project