如何在React中自定义新的google oauth按钮?

问题描述 投票:0回答:1

我正在使用

@react-oauth/google
包在我的应用程序中对用户进行身份验证。然而,我们的后端是预先构建的,它需要在凭证响应中返回 JWT 令牌。
@react-oauth/google
包提供了
credentialsResponse
,但仅包含
GoogleLogin
组件或
useGoogleOneTapLogin
回调中的
onSuccess
钩子。

目前,我按以下方式使用

GoogleLogin
组件:

PS:我已经按照文档中指定的方式在 App.jsx 中设置了

GoogleOAuthProvider
及其工作

import {
  GoogleLogin,
  useGoogleLogin,
  useGoogleOneTapLogin,
} from "@react-oauth/google";

export const GoogleLoginButton = () => {
  const onGoogleSuccess = async (tokenResponse) => {
    try {
      const userData = jwtDecode(tokenResponse?.credential);

      if (isSignup) {
        // This is later used to send the credential JWT token to the backend
        setGoogleRes({ ...userData, ...tokenResponse });
      } else {
        loginUser(userData, tokenResponse);
      }
    } catch (error) {
      setOpen(true);
      setToastData(ToastConstant.SOMETHING_WENT_WRONG);
      console.log("Google fetch error", { error });
    }
  };

  const onGoogleError = (error) => {
    setGoogleRes(null);
    setOpen(true);
    setToastData(ToastConstant.SOMETHING_WENT_WRONG);
  };

  return (
    <GoogleLogin
      onSuccess={onGoogleSuccess}
      onFailure={onGoogleError}
      text="continue_with"
      theme="outline"
      width="100%"
      containerProps={{
        style: {
          width: "100% !important",
        },
      }}
    />
  );
};

但是,我想要一个与我的网站主题相似的自定义按钮。我想广泛自定义按钮的 UI,甚至更改显示的文本。我进行了广泛的搜索,但似乎大多数自定义 Google OAuth 按钮的库都已被弃用,只有这个库看起来足够好用。

有人可以提供一种在 React 中创建自定义 Google OAuth 按钮的方法,其中 onSuccess 回调也接收凭证 JWT 令牌吗?

提前谢谢您!

reactjs oauth-2.0 google-oauth deprecated react-google-login
1个回答
0
投票
import { useGoogleLogin } from '@react-oauth/google';

const login = useGoogleLogin({
  onSuccess: tokenResponse => console.log(tokenResponse),
});

<MyCustomButton onClick={() => login()}>Sign in with Google 🚀</MyCustomButton>;

© www.soinside.com 2019 - 2024. All rights reserved.