The guide to adding Google login to your React app
How To Integrate Google Login in React by Easy way
we use
npm install @react-oauth/google
for Axios and google icon
npm install axios react-icons
you can visit documentation from here but
step 1 :
Get your Google API client ID
Key Point: Add both http://localhost
and http://localhost:<port_number>
to the Authorized JavaScript origins box for local tests or development.
and
Configure your OAuth Consent Screen
step 2 :
in main.js or app.js
Wrap your application with GoogleOAuthProvider
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import { GoogleOAuthProvider } from '@react-oauth/google';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<GoogleOAuthProvider clientId={'9r8f39.apps.googleusercontent.com'}>
<App />
</GoogleOAuthProvider>
</React.StrictMode>,
)
step 3 :
let's make reusable components 😎😎
its be look this
import React,{useState,useEffect} from 'react'
import { FcGoogle } from "react-icons/fc";
import { useGoogleLogin } from "@react-oauth/google";
import axios from "axios";
const LoginByGoogle = () => {
const [user, setUser] = useState([]);
const [userProfile, setUserProfile] = useState([]);
const handlLogin = useGoogleLogin({
onSuccess: (GoogleResponse) => {
setUser(GoogleResponse)
console.log('-----GoogleResponse-----');
console.log(GoogleResponse);
},
onError: (error) => console.log("Login Failed:", error)
});
useEffect(() => {
if (user) {
axios
.get(
`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${user.access_token}`,
{
headers: {
Authorization: `Bearer ${user.access_token}`,
Accept: "application/json",
},
}
)
.then((res) => {
console.log('---- UserProfile-------');
console.log(res.data);
setUserProfile(res.data);
})
.catch((err) => console.log(err));
}
}, [user]);
return (
<div className="shadow-2xl">
<button
type="button"
style={{
backgroundColor: 'white',
color: 'black',
padding: '0.75rem 1.5rem',
borderRadius: '0.5rem',
cursor: 'pointer',
outline: 'none',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
border: 'none',
}}
onClick={handlLogin}
>
<FcGoogle style={{marginRight:'14px'}} />
Sign in with Google
</button>
</div>
);
};
export default LoginByGoogle;
we get it in console
-----GoogleResponse-----
{
"access_token": "ya29.a0AfB_byCwd9",
"token_type": "Bearer",
"expires_in": 39,
"scope": "email sdfsf",
"authuser": "10",
"prompt": "none"
}
---- UserProfile-------
{
"id": "100971739391261646651",
"email": "kh@gmail.com",
"verified_email": true,
"name": "k",
"given_name": "kh",
"family_name": "m",
"picture": "https://lh3.google ": "dg"
}
_**
now you can add data profile in local storage
or database
**_
Top comments (0)