프론트엔드 첫걸음

구글로그인 추가 본문

개발 공부/React

구글로그인 추가

차정 2022. 10. 20. 00:39

설치

 npm install @react-oauth/google@latest
 
 npm install jwt-decode

 

index.html

/*중략*/
    <title>Sandwich</title>
    <script src="https://accounts.google.com/gsi/client" async defer></script>
  </head>

 

코드

function App() {
  //구글 로그인
  const [user, setUser] = useState({});
  function handleCallbackResponse(response) {
    console.log('Encoded JWT ID token : ' + response.credential);
    var userObject = jwt_decode(response.credential);
    console.log(userObject);
    setUser((prev) => {
      return { ...prev, userObject };
    });
    console.log(user);

    document.getElementById('signInDiv').hidden = true;
  }
  function handleSignOut(event) {
    setUser({});
    document.getElementById('signInDiv').hidden = false;
  }
  useEffect(() => {
    /* global google */

    google.accounts.id.initialize({
      client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID,
      callback: handleCallbackResponse,
    });

    google.accounts.id.renderButton(
      document.getElementById('signInDiv'),
      {
        theme: 'outline',
        size: 'large',
      }
    );

    google.accounts.id.prompt();
   
  }, [user]);
  
  
  return (
  
    <div>
      <div id='signInDiv' />
    </div>
  
  )
  
 }

 

 

[출처]

Google Identity Services Login with React (2022 React Google Login)