Login with Google - Reactjs

 Login with Google - Reactjs




Install React-google-login NPM package.

Open App.js and import GoogleLogin from package
import GoogleLogin from 'react-google-login';

Now just add Google Login button with Client ID
<GoogleLogin
clientId="Your_own_client_ID.googleusercontent.com"
buttonText="Login with Google"
onSuccess={pass}
onFailure={fail}
cookiePolicy={'single_host_origin'}
/>                                                        


Just add two handles for onSuccess 
const fail = (result) =>{
alert(result.error);
}

and for onFailure
const pass = (googleData)=>{
console.log(googleData);
}


Import useState for const such as username, user email and photo
import { useState } from 'react';

Const for username
const [username, setusername] = useState();

Const for Email
const [userEmail, setUserEmail] = useState();

Const for Photo
const [userpic, setuserpic] = useState();


By default these const are empty, you have to fill the value by setState under success handle.
setusername(googleData.profileObj.name);
setUserEmail(googleData.profileObj.email);
setuserpic(googleData.profileObj.imageUrl);


Now you can use these values to display username, email and photo.
<img src={userpic}/>
<p><b>{username}</b></p>
<p><b>{userEmail}</b></p>


Demo Video: