[React + TypeScript] 구글로그인 😶‍🌫️

이진경·2023년 2월 20일
1

👩‍💻 REACT

목록 보기
10/10

오늘은 구글로그인에 대해 적어보려고 한당...
2차 프로젝트에서 시도했던 구글로그인 결국 실패하고 협업나와서 다시 만났다 ( 어 안녕 ) 😡

지금 이 블로그를 쓸 수 있다는건? 바로 성공했다는 뜻 🥴 유후

우선 구글 클라우드 플랫폼에 애플리케이션 등록은 다 했다 치고!! 코드만 회고해보려고 한다.


✅ 구글 로그인 코드 작성하기

1️⃣ @react-oauth/google 설치하기

💡 yarn add @react-oauth/google@latest

@react-oauth/google을 설치하면 구글이 인스턴스화 해놓은 컴포넌트들을 사용할 수 있다

2️⃣ GoogleOAuthProvider 사용하기

아래에서 useGoogleLogin을 사용할건데 useGoogleLoginGoogleOAuthProvider내부에서 사용해야 하기 때문에 사용되는 범위에 GoogleOAuthProvider을 작성해준다.

그리고 꼭 해당 컴포넌트에 clientId를 입력해준다.
clientId.env 파일에 작성해서 git에서 관리되지 않게 주의한다! 🤫

userLogin.tsx

const googleOauthClientId = process.env.NEXT_PUBLIC_GOOGLE_OAUTH_CLIENT_ID!;

<GoogleOAuthProvider clientId={googleOauthClientId}>  
     <div>
       <GoogleLoginBtn />
     </div>
</GoogleOAuthProvider>

3️⃣ useGooGleLogin 사용하기

export const GoogleLoginBtn = memo(() => {
    const googleLoginOnSuccess = useGoogleLoginSuccessHandler();

    const loginButtonOnClick = useGoogleLogin({
        onSuccess: async (response) => {
            await googleLoginOnSuccess(response.access_token);
        },
        onError: (error) => {
            console.log(error);
        },
    });

    return (
        <button onClick={() => loginButtonOnClick()} >
            <img src="https://www.svgrepo.com/show/355037/google.svg" />
            <span>Continue with Google</span>
        </button>
    );
});
  • 구글 로그인 버튼을 클릭하고 로그인 성공 또는 실패시의 로직을 작성해준다.
  • 버튼 onClick 됐을때 해당함수가 실행될 수 있도록 한다.


이렇게만 보면 너무 쉬운 구글로그인 🥹 나는 왜이리 고생했는가..

profile
멋찐 프론트엔드 개발자가 되자!

4개의 댓글

comment-user-thumbnail
2023년 2월 20일

루피사진 width 300 으로 부탁요 ㅠ

1개의 답글
comment-user-thumbnail
2023년 2월 20일

😂👏👏👏👏👏👏👏👏👏👏👏👏👏 -메타본 인턴 일동-

1개의 답글