Apply useAuth0 hook and loginWithReditect to Add User Login to React Application

InstructorWill Johnson

Share this video with your friends

Send Tweet

Create a buttons folder the src/components folder

Create a login-button.js file and add the following code:

import { useAuth0 } from "@auth0/auth0-react";
import React from "react";

export const LoginButton = () => {
  const { loginWithRedirect } = useAuth0();

  const handleLogin = async () => {
    await loginWithRedirect({
      appState: {
        returnTo: "/profile",
      },
    });
  };

  return (
    <button className="button__login" onClick={handleLogin}>
      Log In
    </button>
  );
};

loginWithRedirect() redirects to the Auth0 /authorize endpoint to start the authentication process. You can pass a configuration object to this method to customize the login experience.

Setting up the value of appState.returnTo to "/profile", you are telling the Auth0 React SDK to: When my users log in with Auth0 and return to my React application, take them to the "Profile" page.

If you don't set up this appState.returnTo option, your users will be redirected by default to the / path after they log in.