Using google sign in button with react
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.
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 }) })
Now you can use this React Google Login NPM package that encapsulates all the setup work. You can just pass options to the component only.
import React from 'react';import ReactDOM from 'react-dom';import GoogleLogin from 'react-google-login';// orimport { GoogleLogin } from 'react-google-login'; const responseGoogle = (response) => { console.log(response);} ReactDOM.render( <GoogleLogin clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com" buttonText="Login" onSuccess={responseGoogle} onFailure={responseGoogle} cookiePolicy={'single_host_origin'} />, document.getElementById('googleButton'));
The code is from the package's documentation.