Skip to content

Instantly share code, notes, and snippets.

@ZoeLiao
Last active July 10, 2020 15:31
Show Gist options
  • Save ZoeLiao/c2f79a3137993a345b0c3310e15c5ab5 to your computer and use it in GitHub Desktop.
Save ZoeLiao/c2f79a3137993a345b0c3310e15c5ab5 to your computer and use it in GitHub Desktop.
react_google_sigin_siginout.js
import React, { Component } from 'react'
import { GoogleLogin, GoogleLogout } from 'react-google-login';
const CLIENT_ID = '<your Client ID>';
class GoogleBtn extends Component {
constructor(props) {
super(props);
this.state = {
isLogined: false,
accessToken: ''
};
this.login = this.login.bind(this);
this.handleLoginFailure = this.handleLoginFailure.bind(this);
this.logout = this.logout.bind(this);
this.handleLogoutFailure = this.handleLogoutFailure.bind(this);
}
login (response) {
if(response.accessToken){
this.setState(state => ({
isLogined: true,
accessToken: response.accessToken
}));
}
}
logout (response) {
this.setState(state => ({
isLogined: false,
accessToken: ''
}));
}
handleLoginFailure (response) {
alert('Failed to log in')
}
handleLogoutFailure (response) {
alert('Failed to log out')
}
render() {
return (
<div>
{ this.state.isLogined ?
<GoogleLogout
clientId={ CLIENT_ID }
buttonText='Logout'
onLogoutSuccess={ this.logout }
onFailure={ this.handleLogoutFailure }
>
</GoogleLogout>: <GoogleLogin
clientId={ CLIENT_ID }
buttonText='Login'
onSuccess={ this.login }
onFailure={ this.handleLoginFailure }
cookiePolicy={ 'single_host_origin' }
responseType='code,token'
/>
}
{ this.state.accessToken ? <h5>Your Access Token: <br/><br/> { this.state.accessToken }</h5> : null }
</div>
)
}
}
export default GoogleBtn;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment