2023-10-04 15:13:05 +00:00
|
|
|
import { FC, useEffect, useRef, useCallback, useState } from "react";
|
2023-09-01 11:12:30 +00:00
|
|
|
import Script from "next/script";
|
|
|
|
|
|
|
|
export interface IGoogleLoginButton {
|
2023-10-04 15:13:05 +00:00
|
|
|
clientId: string;
|
2023-09-01 11:12:30 +00:00
|
|
|
handleSignIn: React.Dispatch<any>;
|
|
|
|
}
|
|
|
|
|
2023-10-04 15:13:05 +00:00
|
|
|
export const GoogleLoginButton: FC<IGoogleLoginButton> = (props) => {
|
|
|
|
const { handleSignIn, clientId } = props;
|
|
|
|
// refs
|
2023-09-01 11:12:30 +00:00
|
|
|
const googleSignInButton = useRef<HTMLDivElement>(null);
|
2023-10-04 15:13:05 +00:00
|
|
|
// states
|
2023-09-01 11:12:30 +00:00
|
|
|
const [gsiScriptLoaded, setGsiScriptLoaded] = useState(false);
|
|
|
|
|
|
|
|
const loadScript = useCallback(() => {
|
|
|
|
if (!googleSignInButton.current || gsiScriptLoaded) return;
|
|
|
|
|
|
|
|
(window as any)?.google?.accounts.id.initialize({
|
2023-10-04 15:13:05 +00:00
|
|
|
client_id: clientId,
|
2023-09-01 11:12:30 +00:00
|
|
|
callback: handleSignIn,
|
|
|
|
});
|
|
|
|
|
|
|
|
try {
|
|
|
|
(window as any)?.google?.accounts.id.renderButton(
|
|
|
|
googleSignInButton.current,
|
|
|
|
{
|
|
|
|
type: "standard",
|
|
|
|
theme: "outline",
|
|
|
|
size: "large",
|
|
|
|
logo_alignment: "center",
|
|
|
|
text: "signin_with",
|
2023-12-06 11:12:57 +00:00
|
|
|
} as GsiButtonConfiguration // customization attributes
|
2023-09-01 11:12:30 +00:00
|
|
|
);
|
|
|
|
} catch (err) {
|
|
|
|
console.log(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
(window as any)?.google?.accounts.id.prompt(); // also display the One Tap dialog
|
|
|
|
|
|
|
|
setGsiScriptLoaded(true);
|
2023-12-06 11:12:57 +00:00
|
|
|
}, [handleSignIn, gsiScriptLoaded, clientId]);
|
2023-09-01 11:12:30 +00:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if ((window as any)?.google?.accounts?.id) {
|
|
|
|
loadScript();
|
|
|
|
}
|
|
|
|
return () => {
|
|
|
|
(window as any)?.google?.accounts.id.cancel();
|
|
|
|
};
|
|
|
|
}, [loadScript]);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<>
|
|
|
|
<Script src="https://accounts.google.com/gsi/client" async defer onLoad={loadScript} />
|
2023-12-10 10:18:10 +00:00
|
|
|
<div className="w-full overflow-hidden rounded" id="googleSignInButton" ref={googleSignInButton} />
|
2023-09-01 11:12:30 +00:00
|
|
|
</>
|
|
|
|
);
|
|
|
|
};
|