npm i @react-oauth
npm i jwt-decode
main.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import './index.css' import 'regenerator-runtime/runtime'; import { GoogleOAuthProvider } from "@react-oauth/google"; const clientId = ""; import App from './App.jsx' createRoot(document.getElementById('root')).render( <StrictMode> <GoogleOAuthProvider clientId={clientId}> <App /> </GoogleOAuthProvider> </StrictMode> ) |
App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import React, { useState } from "react"; import { GoogleOAuthProvider, useGoogleOneTapLogin } from "@react-oauth/google"; import { jwtDecode } from "jwt-decode"; const App = () => { const clientId = ""; // State to store user profile information const [userProfile, setUserProfile] = useState(null); useGoogleOneTapLogin({ onSuccess: (credentialResponse) => { console.log("Login successful:", credentialResponse); // Decode the user's JWT token to extract profile information const decoded = jwtDecode(credentialResponse.credential); console.log("Decoded Token:", decoded); // Update the user profile state setUserProfile({ name: decoded.name, email: decoded.email, picture: decoded.picture, }); }, onError: () => { console.log("Login failed"); }, use_fedcm_for_prompt: true, // Enable the browser to mediate the sign-in flow }); return ( <GoogleOAuthProvider clientId={clientId}> <div style={{ textAlign: "center", marginTop: "50px" }}> <h1>Google One Tap Login Example</h1> {userProfile ? ( // Display user profile information after login <div style={{ marginTop: "20px" }}> <img src={userProfile.picture} alt="Profile" style={{ borderRadius: "50%", width: "100px", height: "100px" }} /> <h2>Welcome, {userProfile.name}!</h2> <p>Email: {userProfile.email}</p> </div> ) : ( <p>The browser mediates the sign-in flow seamlessly using FedCM.</p> )} </div> </GoogleOAuthProvider> ); }; export default App; |
App.css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
.App { text-align: center; padding: 20px; } .user-profile { text-align: center; margin-top: 20px; } .profile-picture { width: 100px; height: 100px; border-radius: 50%; object-fit: cover; margin-bottom: 10px; } h1 { font-size: 2rem; margin-bottom: 20px; } p { font-size: 1rem; color: #555; } |