React Google login with example

Today we will discuss about Google login in React. We will use JS SDK of Google for the login. This going to be very easy with React Google Login tutorial. So let’s get start with the react google login with example.

Before get started google login integration in your React Application, We need a React Project. If you don’t know how to create a new project. Follow this tutorial.

Create Client ID

Before you can integrate Google Sign-In into your website, you must create a client ID, which you need to call the sign-in API.

To create a Google API Console project and client ID, go to the APIs & Services dashboard and then follow the below video:

Add a Placeholder

We need to add a placeholder for the signin button. To add the placeholder open App.js file and replace the render function.

render() {

        return (
            <div className="row mt-5">  
                <div className="col-md-12">
                    <h2 className="text-left">Google Login Demo</h2>
                    <div className="card mt-3">
                        <div className="card-body">
                            
                            <div className="row mt-5 mb-5">
                                <div className="col-md-4 mt-2 m-auto ">
                                    <button className="loginBtn loginBtn--google" ref="googleLoginBtn">
                                        Login with Google
                                    </button>
                                </div>    
                            </div>
                        
                        </div>
                    </div>
                </div>
            </div>
        );
    }

Next, Need to give some styling, Open your index.css file and put the below css

/* Shared */
.loginBtn {
    box-sizing: border-box;
    position: relative;
    /* width: 13em;  - apply for fixed size */
    margin: 0.2em;
    padding: 0 15px 0 46px;
    border: none;
    text-align: left;
    line-height: 34px;
    white-space: nowrap;
    border-radius: 0.2em;
    font-size: 16px;
    color: #FFF;
  }
  .loginBtn:before {
    content: "";
    box-sizing: border-box;
    position: absolute;
    top: 0;
    left: 0;
    width: 34px;
    height: 100%;
  }
  .loginBtn:focus {
    outline: none;
  }
  .loginBtn:active {
    box-shadow: inset 0 0 0 32px rgba(0,0,0,0.1);
  }
  
  
  /* Google */
  .loginBtn--google {
    /*font-family: "Roboto", Roboto, arial, sans-serif;*/
    background: #DD4B39;
  }
  .loginBtn--google:before {
    border-right: #BB3F30 1px solid;
    background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/14082/icon_google.png') 6px 6px no-repeat;
  }
  .loginBtn--google:hover,
  .loginBtn--google:focus {
    background: #E74B37;
  }

Load the Google Platform Library

Add the below method in your component file. I am going to add in my App.js file

googleSDK() {

  window['googleSDKLoaded'] = () => {
    window['gapi'].load('auth2', () => {
      this.auth2 = window['gapi'].auth2.init({
        client_id: 'YOUR_CLIENT_ID',
        cookiepolicy: 'single_host_origin',
        scope: 'profile email'
      });
      this.prepareLoginButton();
    });
  }

  (function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "https://apis.google.com/js/platform.js?onload=googleSDKLoaded";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'google-jssdk'));

}

Here, Change the YOUR_CLIENT_ID with your client id, Which we have created at the start of this tutorial.

You may notice that We have created a googleSDKLoaded method. We have set the callback when the Google Platform Library will loaded. This method will initialize the google login

Next, Call the above method from the componentDidMount() method

componentDidMount() {
  this.googleSDK();
}

Attach Click Handler

Add the below method in your component file. I am going to add in my App.js file

prepareLoginButton = () => {

console.log(this.refs.googleLoginBtn);

this.auth2.attachClickHandler(this.refs.googleLoginBtn, {},
    (googleUser) => {

    let profile = googleUser.getBasicProfile();
    console.log('Token || ' + googleUser.getAuthResponse().id_token);
    console.log('ID: ' + profile.getId());
    console.log('Name: ' + profile.getName());
    console.log('Image URL: ' + profile.getImageUrl());
    console.log('Email: ' + profile.getEmail());
    //YOUR CODE HERE


    }, (error) => {
    alert(JSON.stringify(error, undefined, 2));
    });

}

You might noticed that We have already call this method inside the ` googleSDKLoaded .

This method will attach the click handler. When user click on Google signin button google will open the login dialog box.

After the complete all the above steps, our component will looks like this

import React, { Component } from 'react';

class App extends Component {

    componentDidMount() {
        this.googleSDK();
        console.log('sfsfd');
    }

    prepareLoginButton = () => {

    console.log(this.refs.googleLoginBtn);

    this.auth2.attachClickHandler(this.refs.googleLoginBtn, {},
        (googleUser) => {

        let profile = googleUser.getBasicProfile();
        console.log('Token || ' + googleUser.getAuthResponse().id_token);
        console.log('ID: ' + profile.getId());
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail());
        //YOUR CODE HERE


        }, (error) => {
            alert(JSON.stringify(error, undefined, 2));
        });

    }

    googleSDK = () => {

        window['googleSDKLoaded'] = () => {
          window['gapi'].load('auth2', () => {
            this.auth2 = window['gapi'].auth2.init({
              client_id: '764194037935-hkai71dhmgitqvsmv7alnj7ivcab3fvt.apps.googleusercontent.com',
              cookiepolicy: 'single_host_origin',
              scope: 'profile email'
            });
            this.prepareLoginButton();
          });
        }
    
        (function(d, s, id){
          var js, fjs = d.getElementsByTagName(s)[0];
          if (d.getElementById(id)) {return;}
          js = d.createElement(s); js.id = id;
          js.src = "https://apis.google.com/js/platform.js?onload=googleSDKLoaded";
          fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'google-jssdk'));
    
    }
  
    render() {

        return (
            <div className="row mt-5">  
                <div className="col-md-12">
                    <h2 className="text-left">Google Login Demo</h2>
                    <div className="card mt-3">
                        <div className="card-body">
                            
                            <div className="row mt-5 mb-5">
                                <div className="col-md-4 mt-2 m-auto ">
                                    <button className="loginBtn loginBtn--google" ref="googleLoginBtn">
                                        Login with Google
                                    </button>
                                </div>    
                            </div>
                        
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

export default App;

Running application:

Run the application using npm start

Preview

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *