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

57 Comments

  1. viagra without a prescription said:

    I enjoy you because of all of the effort on this blog. Betty delights in carrying out internet research and it’s easy to see why. A lot of people hear all about the compelling form you convey both interesting and useful guidance by means of the blog and attract contribution from other individuals about this area and my child has always been becoming educated a great deal. Enjoy the remaining portion of the new year. You’re carrying out a brilliant job. https://habebihookahbar.com/

    January 7, 2021
    Reply
  2. viagra without a prescription said:

    I enjoy you because of all of the effort on this blog. Betty delights in carrying out internet research and it’s easy to see why. A lot of people hear all about the compelling form you convey advantageous guidance by means of the blog and attract contribution from other individuals about this area and my child has always been becoming educated a great deal. Enjoy the remaining portion of the new year. You’re carrying out a brilliant job. https://habebihookahbar.com/

    January 7, 2021
    Reply
  3. cialis tablets said:

    A lot of thanks for each of your hard work on this web page. Kim really likes going through investigation and it’s really easy to understand why. Many of us know all of the dynamic method you make powerful strategies on this web blog and as well as improve participation from people on that issue so our girl is in fact learning a lot of things. Have fun with the remaining portion of the new year. You are conducting a really good job. https://lvagroupinc.com/

    January 7, 2021
    Reply
  4. cialis generic said:

    I’m also commenting to let you be aware of of the cool discovery my child encountered checking your blog. She came to understand a lot of details, including how it is like to have a marvelous coaching heart to get folks easily fully grasp a variety of complicated issues. You actually did more than my desires. I appreciate you for delivering such good, dependable, edifying and also cool guidance on that topic to Ethel. https://azzaroelectric.com/

    January 7, 2021
    Reply
  5. purchase kamagra said:

    Needed to send you this very small word to finally thank you so much yet again relating to the stunning thoughts you have shared on this site. This is so unbelievably open-handed of people like you to allow extensively all that a lot of folks could possibly have distributed as an e-book in order to make some cash for their own end, especially considering the fact that you could have done it if you considered necessary. The good ideas also acted as the easy way to be sure that most people have a similar dream just like mine to find out a lot more in respect of this condition. I’m certain there are lots of more enjoyable moments ahead for individuals that find out your blog. https://jlsmithjax.com/

    January 7, 2021
    Reply
  6. purchase trazodone said:

    I simply wished to thank you very much yet again. I do not know what I would have undertaken without those tips shared by you regarding this theme. Previously it was the terrifying setting in my view, nevertheless understanding your well-written technique you solved the issue took me to weep with joy. Now i’m thankful for your support and thus trust you really know what an amazing job you were putting in training the others via your website. Most probably you haven’t met any of us. https://desyreltrazodone.com/

    January 8, 2021
    Reply
  7. pamelor pills said:

    I am also commenting to let you know of the great encounter my friend’s daughter found reading through your web page. She figured out numerous issues, not to mention what it’s like to have an amazing giving mood to have men and women really easily have an understanding of selected hard to do subject areas. You really exceeded our own expectations. Many thanks for imparting the interesting, safe, explanatory and even easy thoughts on the topic to Janet. https://pamelornortriptyline.com/

    January 9, 2021
    Reply
  8. cheap olanzapine said:

    Thanks for the advice on credit repair on this excellent site. Some tips i would tell people should be to give up this mentality that they may buy currently and fork out later. Being a society many of us tend to make this happen for many issues. This includes vacation trips, furniture, along with items we’d like. However, you’ll want to separate your current wants out of the needs. If you are working to boost your credit score actually you need some trade-offs. For example you’ll be able to shop online to save cash or you can look at second hand merchants instead of high-priced department stores pertaining to clothing. https://zyprexaolanzapine.com/#

    January 10, 2021
    Reply
  9. Shanika Puthiyamadam said:

    Can I move a secondary Tumblr blog to a different account?

    January 15, 2021
    Reply
  10. Reyes Hockley said:

    What is the best short or from home creative writing course available in London?

    January 16, 2021
    Reply
  11. clarkericky said:

    Thanks for the tips on credit repair on all of this blog. What I would advice people is to give up the mentality that they can buy now and pay later. As a society we tend to do this for many things. This includes vacations, furniture, and items we want. However, you need to separate your wants from all the needs. While you are working to improve your credit score you have to make some sacrifices. For example you can shop online to save money or you can go to second hand stores instead of expensive department stores for clothing. Life Experience Degrees

    January 20, 2021
    Reply
  12. stevesmith said:

    My wife and i were very satisfied when Peter managed to finish up his survey while using the precious recommendations he received when using the weblog. It is now and again perplexing to simply possibly be offering tips which usually the others might have been trying to sell. We see we now have you to thank for this. These illustrations you made, the straightforward website navigation, the relationships your site make it possible to promote – it is mostly terrific, and it is making our son in addition to us recognize that this theme is satisfying, which is certainly unbelievably serious. Thanks for the whole thing! Life Experience Degree

    January 20, 2021
    Reply
  13. Dante said:

    Your style is really unique in comparison to other folks I’ve read stuff from.
    Thanks for posting when you have the opportunity, Guess I
    will just book mark this web site.

    Also visit my blog; cheap flights

    January 31, 2021
    Reply
  14. Fletcher said:

    Hello there! This blog post could not be written much better!
    Looking through this article reminds me of my previous roommate!
    He always kept preaching about this. I most certainly will send this post to him.

    Pretty sure he will have a great read. Thanks for sharing!

    Feel free to surf to my homepage cheap flights

    February 1, 2021
    Reply
  15. Chong Lolar said:

    This is a very interesting article. Please, share more like this!

    February 1, 2021
    Reply
  16. Tayla said:

    Hi there, I found your website by the use of Google even as looking for a related subject, your website got here up,
    it appears to be like great. I have bookmarked it in my google bookmarks.

    Hi there, simply changed into alert to your blog via Google,
    and located that it is truly informative. I’m going to
    watch out for brussels. I’ll be grateful when you proceed
    this in future. Lots of people can be benefited from your writing.
    Cheers!

    Look at my web-site :: cheap flights (tinyurl.com)

    February 2, 2021
    Reply
  17. Magda said:

    This post is genuinely a fastidious one it assists
    new net people, who are wishing in favor of blogging.

    Also visit my webpage cheap flights

    February 2, 2021
    Reply
  18. Harvey said:

    I am in fact pleased to glance at this webpage posts which carries tons of valuable information, thanks for providing such data.

    my homepage cheap flights (tinyurl.com)

    February 3, 2021
    Reply
  19. Ekonomia said:

    Zwierzeta sa z reguly moimi przyjacilomi, a ja nie zjadam swoich przyjaciol. G. Shaw & TM… 🙂

    February 4, 2021
    Reply
  20. Aluminium Metale said:

    Zycie jest tylko przechodnim plocieniem, Nedznym aktorem, ktory swa role Przez pare godzin wygrawszy na scenie W nicosc przepada – powiescia idioty, Glosna, wrzaskliwa, a nic nie znaczaca. – William Shakespeare

    February 6, 2021
    Reply
  21. WWW.Pianino.xmc.pl said:

    Zycie przesycone jest abstrakcja i mozemy cos z niego zrozumiec jedynie dzieki intuicji. – David Lynch

    February 8, 2021
    Reply
  22. Jane said:

    bookmarked!!, I love your blog!

    Feel free to visit my web-site cheap flights; http://tinyurl.com/,

    February 12, 2021
    Reply
  23. Matthias said:

    Αn authoritative ⲣage can pass on search ranking оr hyperlink juice to otheг pаges on youг web-site.

    my web site; google escorts

    February 12, 2021
    Reply
  24. Norwegia said:

    Jaki jest sens zycia? To zalezy od tego, jakie zycie masz na mysli. – Colleen Hoover

    February 14, 2021
    Reply
  25. sildenafil time of effectiveness said:

    sildenafil time of effectiveness

    sildenafil time of effectiveness

    February 14, 2021
    Reply
  26. Rolland said:

    Upewnij się, że dzierżysz teraz wystarczająco dużo czasu, aby ɡo przeczytać, lub zawsze
    możesz ցo dodać do zakładek i przeczytać później!

    Feel free to surf to my webpage pozycjonowanie stron ile kosztuje

    February 14, 2021
    Reply
  27. Jbbnguany said:

    cialis pour bander cialis 1omg does cialis work on women

    February 16, 2021
    Reply
  28. Filozofia.XMC.pl said:

    Bardzo ciekawy blog, rzeczowy i wywazony. Od dzisiaj zagladam regularnie. Pozdrowienia 🙂

    February 17, 2021
    Reply
  29. Noe said:

    College Physics Sears Zemansky Young Pdf Siddhartha In Hindi

    Here is my blog … wordpress.com

    February 17, 2021
    Reply
  30. Latosha said:

    It has everything covered, even your kinky side!

    Look at my web site; escort antwerp

    February 20, 2021
    Reply
  31. USA Blog said:

    Fantastyczny tekst Brawo! szczegolnie spodobala mi sie szata graficzna twojego bloga 🙂 zapraszam do siebie… http://www.xmc.pl

    February 20, 2021
    Reply
  32. goverment viagra fundong for servoce said:

    goverment viagra fundong for servoce

    goverment viagra fundong for servoce

    February 23, 2021
    Reply
  33. Siobhan said:

    Piece of writing writing is also a fun, if you be acquainted with after that
    you can write if not it is difficult to write.

    My website – instagram takipci satisi

    February 23, 2021
    Reply
  34. Alda said:

    Definitely believe that which you stated. Your favorite justification seemed to be on the web the easiest thing to be aware of.
    I say to you, I certainly get irked while people think about worries that they plainly don’t know
    about. You managed to hit the nail upon the top and also defined out the
    whole thing without having side-effects , people can take a signal.
    Will likely be back to get more. Thanks

    my web-site :: shell php

    February 23, 2021
    Reply
  35. Japonia Gospodarka said:

    Zycie bez zajec naukowych i literackich jest smiercia i grobem zywego czlowieka. – Seneka Zapraszam takze do siebie USA Edukacja

    February 24, 2021
    Reply
  36. Murray said:

    Hmm is anyone else encountering problems with the pictures
    on this blog loading? I’m trying to figure out if its a problem on my end or if
    it’s the blog. Any responses would be greatly appreciated.

    Here is my blog: antalya haber oku

    February 25, 2021
    Reply

Leave a Reply

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