Google OAuth in React

sathyan b
Nov 8, 2023

--

React Login

Let’s create a simple Google OAuth Login in react-18.

Prerequisite:

You need a Google Client ID. To get that,
https://www.youtube.com/watch?v=HtJKUQXmtok

(Thanks to the Cooper Codes).

Libraries to use:

  "gapi-script": "^1.2.0" //google-oAuth api's
"@leecheuk/react-google-login": "^5.4.1" //Login and Logout component

Let’s dive in:

Step 1: Initialize

Use the below code to initialize the Google init call.

import { gapi } from "gapi-script";

function start() {
gapi.client.init({
clientId: "your-client-id",
scope: "",
});
}
gapi.load("client:auth2", start);

Step 2: Log in

To create a Login button,

import { GoogleLogin } from "@leecheuk/react-google-login";

<GoogleLogin
clientId="your-client-id"
buttonText="Login"
onSuccess={onSuccess}
onFailure={onError}
cookiePolicy={"single_host_origin"}
/>

Step 3: Log out

To create a Logout button,

import { GoogleLogout } from "@leecheuk/react-google-login";

<GoogleLogout
clientId="your-client-id"
buttonText="Logout"
onLogoutSuccess={logout}
/>

Run your app.

Thank you.

--

--