DEV Community

Cover image for GitHub login with React Js
Automaton
Automaton

Posted on

GitHub login with React Js

To implement a login feature using GitHub in a React application, you will need to use the GitHub API to authenticate the user and retrieve their information.
Here is a breakdown:

  1. Install the react-github-login library
    npm install react-github-login

  2. Import the GitHubLogin component

import { GitHubLogin } from 'react-github-login';

  1. Add the GitHubLogin component to your React component and pass in your client_id and redirect_uri as props
const MyComponent = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [accessToken, setAccessToken] = useState(null);
  const [user, setUser] = useState(null);

  const handleGitHubLoginSuccess = (response) => {
    const { code } = response;
    axios.post('https://github.com/login/oauth/access_token', {
      client_id: 'YOUR_CLIENT_ID',
      client_secret: 'YOUR_CLIENT_SECRET',
      code: code
    })
      .then(result => {
        const accessToken = result.data.access_token;
        localStorage.setItem('access_token', accessToken);
        axios.get(`https://api.github.com/user?access_token=${accessToken}`)
          .then(result => {
            localStorage.setItem('user', JSON.stringify(result.data));
            setIsLoggedIn(true);
            setAccessToken(accessToken);
            setUser(result.data);
          })
          .catch(error => {
            console.log(error);
          });
      })
      .catch(error => {
        console.log(error);
      });
  }

  const handleGitHubLoginFailure = (response) => {
    console.log(response);
  }

  const handleLogout = () => {
    localStorage.removeItem('access_token');
    localStorage.removeItem('user');
    setIsLoggedIn(false);
    setAccessToken(null);
    setUser(null);
  }

  return (
    <>
      <GitHubLogin
        clientId="YOUR_CLIENT_ID"
        redirectUri="YOUR_REDIRECT_URI"
        onSuccess={handleGitHubLoginSuccess}
        onFailure={handleGitHubLoginFailure}
        className="github-login-button"
      />
      {isLoggedIn && <button onClick={handleLogout}>Logout</button>}
    </>
  )
}

Enter fullscreen mode Exit fullscreen mode

In this example, the component state is managed using the useState hook. The handleGitHubLoginSuccess, handleGitHubLoginFailure, and handleLogout functions are defined as arrow functions within the component. The component render the login button if the user is not logged in and a logout button if the user is logged in. The component also saves the access token and user information in local storage.

Top comments (0)