Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using google sign in button with react

I'm trying to use the google sign in in a react application. While using the sign in button as is outside the application itself works great, when using it within a custom SignIn component I can't get it to work as expected. When the user signs in, the button itself should execute a data-onsuccess method. The problem is that the execution never reaches that method even though the sign in works.

I'm probably missing some react gotcha but I can't really find it. Any help? Find below the html that loads everything and the component itself.

<head>     <meta name="google-signin-scope" content="profile email">     <meta name="google-signin-client_id" content="1234-real-client-id.apps.googleusercontent.com">     <script src="https://apis.google.com/js/platform.js" async defer></script> </head> <body>     <!-- Here is where everything gets displayed -->     <div id="app"></div>      <!-- The file with the js code -->     <script src="/js/main.js"></script> </body>   var SignIn = React.createClass({     onSignIn : function (google_user) {         // I want this method to be executed     },      render : function() {         return (             <div className="g-signin2" data-onsuccess={this.onSignIn} data-theme="dark" />         );     } }); 

Notice that I didn't paste here irrelevant code ;)

like image 689
ThisIsErico Avatar asked Jul 24 '15 12:07

ThisIsErico


People also ask

Is react Google login deprecated?

We are discontinuing the Google Sign-In JavaScript Platform Library for web. The library will be unavailable for download after the March 31, 2023 deprecation date.


2 Answers

Try adding the onSuccess callback when you initialize the component in componentDidMount().

componentDidMount: function() {    gapi.signin2.render('g-signin2', {      'scope': 'https://www.googleapis.com/auth/plus.login',      'width': 200,      'height': 50,      'longtitle': true,      'theme': 'dark',      'onsuccess': this. onSignIn    });    },  ...

Sources: https://developers.google.com/identity/sign-in/web/build-button, https://github.com/meta-meta/webapp-template/blob/6d3e9c86f5c274656ef799263c84a228bfbe1725/app/Application/signIn.jsx.

like image 81
BradByte Avatar answered Sep 19 '22 21:09

BradByte


I needed to use this in a functional component so thought I would share how I adapted it, I needed to use the useEffectHook which can be used in place of componentDidMount

  useEffect(() => {     window.gapi.signin2.render('g-signin2', {       'scope': 'https://www.googleapis.com/auth/plus.login',       'width': 200,       'height': 50,       'longtitle': true,       'theme': 'dark',       'onsuccess': onSignIn     })   }) 
like image 42
Max Carroll Avatar answered Sep 20 '22 21:09

Max Carroll