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

Bardzo lubię patrzeć i uważam, że ta strona zawiera naprawdę przydatne rzeczy! https://samocholand.pl/samochody/
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/
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/
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/
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/
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/
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/
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/
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/#
Can I move a secondary Tumblr blog to a different account?
What is the best short or from home creative writing course available in London?
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
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
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
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
This is a very interesting article. Please, share more like this!
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)
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
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)
legit online pharmacy price pro pharmacy canada pharmacy online drugstore
Zwierzeta sa z reguly moimi przyjacilomi, a ja nie zjadam swoich przyjaciol. G. Shaw & TM… 🙂
viagra 50 mg viagra and diopoxtamine generic viagra for sale
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
cialis daily walgreens online pharmacy walmart pharmacy viagra
cialis 20 mg sell buy cialis no prescription australia cialis
online discount pharmacy canadian pharmacy review international pharmacies that ship to the usa
viagra for sale onlkne free viagra samples canada safest sites to buy viagra
Zycie przesycone jest abstrakcja i mozemy cos z niego zrozumiec jedynie dzieki intuicji. – David Lynch
online canadian pharmacies canadian pharmacy kingcanadian viagra drug costs
top rated online canadian pharmacies viagra paypal canada payment mental illness
online canadian pharmacies canadian viagra pharmacy
buy viagra no prescription reasons to use viagra over night viagra usa
payday loans in rancho mirage ca cash advance amex platinum do hard money loans
bookmarked!!, I love your blog!
Feel free to visit my web-site cheap flights; http://tinyurl.com/,
Αn authoritative ⲣage can pass on search ranking оr hyperlink juice to otheг pаges on youг web-site.
my web site; google escorts
Jaki jest sens zycia? To zalezy od tego, jakie zycie masz na mysli. – Colleen Hoover
over the counter viagra for sale 50 mg viagra for $1995 where i buy viagra in delhi
real online cash loans aberdeen payday loan installment cash loans for bad credit
cash advance norwalk ca payday loans in texas illegal tribal cash advances
sildenafil time of effectiveness
sildenafil time of effectiveness
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
Surface Chemistry Lecture Volcano Science Project In Tamil
Also visit my web blog pdf file (https://floodbeschpako1978.netlify.app/)
cialis no prescription overnight 200 mg cialis deals online cheap cialis generic online
cialis pour bander cialis 1omg does cialis work on women
Bardzo ciekawy blog, rzeczowy i wywazony. Od dzisiaj zagladam regularnie. Pozdrowienia 🙂
does blue cross cover cialis for bph bula do remedio cialis comprar cialis em curitiba
College Physics Sears Zemansky Young Pdf Siddhartha In Hindi
Here is my blog … wordpress.com
advanced learning loans providers cash advance orange ca cash loans vic park
Jkbose Official Website Download St Xavier School Of Education Patna
Feel free to visit my webpage: ebook, https://canoportra1984.netlify.app/,
Very smooth text.
free robux
It has everything covered, even your kinky side!
Look at my web site; escort antwerp
Fantastyczny tekst Brawo! szczegolnie spodobala mi sie szata graficzna twojego bloga 🙂 zapraszam do siebie… http://www.xmc.pl
goverment viagra fundong for servoce
goverment viagra fundong for servoce
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
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
Zycie bez zajec naukowych i literackich jest smiercia i grobem zywego czlowieka. – Seneka Zapraszam takze do siebie USA Edukacja
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