Gapi not detected when loading React component

I am trying to integrate Google Sign In ( link ) using React.
I found a question that solved this in the past Using the Google login button with answer 2

I reproduced the same steps as mentioned. In my index.html I do

 <script src="https://apis.google.com/js/platform.js?onload=triggerGoogleLoaded" async defer></script> <script type="text/javascript"> function triggerGoogleLoaded() { console.log("google event loaded"); window.dispatchEvent(new Event('google-loaded')); } </script> 

Then my Component looks like

 var LoginButton = React.createClass({ onSignIn: function(googleUser) { console.log("user signed in"); // plus any other logic here }, renderGoogleLoginButton: function() { console.log('rendering google signin button'); gapi.signin2.render('my-signin2', { 'scope': 'https://www.googleapis.com/auth/plus.login', 'width': 200, 'height': 50, 'longtitle': true, 'theme': 'light', 'onsuccess': this.onSignIn }) }, componentDidMount: function() { window.addEventListener('google-loaded',this.renderGoogleLoginButton); }, render: function() { let displayText = "Sign in with Google"; return ( <div class="g-signin2" data-onsuccess="onSignIn"></div> ); } }); export default LoginButton; 

When I run the program using yarn start , I get

 /Users/Harit.Himanshu/bl/sources/webs/google-login/src/LoginButton.js 11:9 error 'gapi' is not defined no-undef 26:13 warning 'displayText' is assigned a value but never used no-unused-vars βœ– 2 problems (1 error, 1 warning) 

The full source code is available at https://github.com/hhimanshu/google-login-with-react

Can someone please help me understand my mistake?

thanks

+10
javascript reactjs google-signin
source share
3 answers

It seems to me that you are loading google apis as a script tag, which we expect to install window.gapi in google api. However, you run eslint or some other check, and it has no idea that window.gapi should exist. It does not work because it sees that you are using an undeclared variable.

A cheap solution is to tell Eslint that you know what you are doing;

 /* global gapi */ 

Put this at the top of your file and eslint will treat gapi as a known global variable.

+11
source share

It worked for me. Put this in componentDidMount or constructor:

 componentDidMount() { window.gapi.load('auth2', () => { // Retrieve the singleton for the GoogleAuth library and set up the client. this.auth2 = window.gapi.auth2.init({ client_id: '436676563344-.apps.googleusercontent.com', cookiepolicy: 'single_host_origin', }); this.auth2.attachClickHandler(this.refs.googleButton, {}, (googleUser) => { this.googleLogin(googleUser.getBasicProfile()); }, (error) => { }); }); } 
+4
source share

You can also try gapi-script package, this package instantly provides gapi, so you do not need to wait for any script to load, just import it and use:

 import { gapi } from 'gapi-script'; 
0
source share

All Articles