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

Will Johnson
InstructorWill Johnson
Share this video with your friends

Social Share Links

Send Tweet
Published a year ago
Updated a year ago

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.

egghead
egghead
~ 23 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today