Login with Google in React JS

Login with Google in React JS

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

In my last post, we learnt how to use google sign-in in a PHP app and hope you all liked it. In this post, we are going to see how to log in with Google in a react app.

All you need is Google API Credential and react-google-login package which you can install using NPM.

Update: Here is the live link to the app what we are going to make.

Google API Credentials

We'll start by getting Google API keys and, for this, you need a google account which I hope we all have one.

Now, go to the below URL and sign in there. Google Cloud Platform

Here, you need to click on the Create Project button. It'll ask you to enter a name for your project.

Enter any name for your project and click Create.

Now go to the homepage of Google Console and from the menu on your left side of the screen, click on OAuth consent screen. Make sure your project is selected which you have created just now.

Give your application a name and click save. It will redirect to a new page and, it will ask you to Create Credentials.

Click on that and select OAuth client ID from the dropdown.

It will ask you for the application type. Select the Web application and hit Create.

Give it a name and a redirect URL.

http://localhost:3000/

All done. It will provide you with your client id and client secret key.

You are now done with the Google API Credentials part.

Let us now install react-google-login package.

To install the package, type the below command in your terminal and hit enter and it will install the package.

npm i react-google-login

Once the package is installed, we can now move to the code part.

We need to create two components in our src directory.

  1. Login.jsx
  2. Logout.jsx
  3. Profile.jsx

Let's see the login component.

Inside your Login.jsx file, paste the following code.

Don't forget to replace the client id in both the components with your client id.

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

const clientId = 
      "your-client-id-here.apps.googleusercontent.com";

function Login(props) {
  function onSuccess(res) {
    props.setUser(res.profileObj);
  }
  function onFailure(res) {
    // console.log(res);
    alert(`Oops! Some error occured: ${res}`);
  }

  return (
    <div>
      <GoogleLogin
        clientId={clientId}
        buttonText="Login"
        onSuccess={onSuccess}
        onFailure={onFailure}
        cookiePolicy={"single_host_origin"}
        isSignedIn={true}
      />
    </div>
  );
}

export default Login;

We are done with the login part and we can now move to the logout part. Below is the code for the logout component. Paste the below code in your Logout.jsx file.

import React from "react";
import { GoogleLogout } from "react-google-login";

const clientId =
      "your-client-id-here.apps.googleusercontent.com";

function Logout(props) {
  function onSuccess(res) {
    props.setUser(null);
  }

  return (
    <div>
      <GoogleLogout
        clientId={clientId}
        buttonText="Logout"
        onLogoutSuccess={onSuccess}
      />
    </div>
  );
}

export default Logout;

We are done with the login and logout component and we are left with the Profile component. Create a new file named Component.jsx and paste the below code.

import React from "react";
import Logout from "./Logout";
import "../stylesheet/Profile.css";

function Profile(props) {
  return (
    <div className="profile-card">
      <img src={props.user.imageUrl} alt="" />
      <h1>{props.user.name}</h1>
      <span>{props.user.email}</span>
      <p>Id: {props.user.googleId}</p>
      <Logout setUser={props.setUser} />
    </div>
  );
}

export default Profile;

Now we need to import both login and profile components in our app component. Here is the code for App.js file. Paste this code in your App.js file.

import React, { useState } from "react";
import Login from "./Login";
import Profile from "./Profile";
import "../stylesheet/App.css";

function App() {
  const [user, setUser] = useState(null);
  return (
    <div className="app">
      {user ? (
        <Profile user={user} setUser={setUser} />
      ) : (
        <Login setUser={setUser} />
      )}
    </div>
  );
}

export default App;

Let's understand the code

Now, what is happening here is we are creating a user state and storing the user profile object in it once the user is logged in.

  const [user, setUser] = useState(null);

In my both login and profile component, I'm passing setUser as a prop so that I can update the user when the user tries to log in and when a user tries to logout in profile component, I'm setting the user state to null.

The ternary operator is helping me to render content conditionally and if you are not familiar with conditional rendering then you can take reference from my post on conditional rendering here.

How to render content conditionally in React JS

I know this is not the best-looking sign-in page but this post is not about CSS styling. If you want to style your index page, you can do by adding a stylesheet named App.css in the same directory and paste the below code.

.app {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

Now we are done with the App.css and we need to style our Profile card. Here is the code for the Profile.css. Copy the below code and paste the code in your Profile.css stylesheet.

.profile-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 300px;
  height: 400px;
  background-color: rgb(252, 231, 231);
  border-radius: 5px;
}

.profile-card > img {
  width: 100px;
  border-radius: 50%;
}

.profile-card > h1 {
  color: rgb(87, 87, 87);
  font-size: 22px;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

.profile-card > span {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  color: rgb(77, 77, 77);
}

.profile-card > p {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  color: rgb(36, 36, 36);
  font-size: 12px;
}

Now, we are done with the login. If you want to test the link, open your terminal and run the below command in your terminal.

npm start    

This will start your app and will open the URL in your default browser.

Use any of your Gmail and it will log you in and will show you email in the alert box.

This was all about how to use 'login with Google in a react app'. Here is the link to the GitHub repo for the complete source code.

ThePratikSah/login-with-google-react-app

If you found my application helpful, please star my repo on GitHub.

I hope you liked my post on Log in with Google in a React App and if you found my post helpful, please share it with your friends and if you have any doubt, feel free to comment below and I'll try to solve your problem ASAP.

Thanks for your time and I'll meet you in my next post. Take care and happy coding🙂!

 
Share this