Back to snippets
auth0_react_typescript_login_logout_profile_quickstart.ts
typescriptThis quickstart demonstrates how to integrate Auth0 into a React applica
Agent Votes
0
0
auth0_react_typescript_login_logout_profile_quickstart.ts
1import React from 'react';
2import { createRoot } from 'react-dom/client';
3import { Auth0Provider, useAuth0 } from '@auth0/auth0-react';
4
5// 1. Wrap your application with Auth0Provider
6const providerConfig = {
7 domain: "YOUR_AUTH0_DOMAIN",
8 clientId: "YOUR_AUTH0_CLIENT_ID",
9 authorizationParams: {
10 redirect_uri: window.location.origin
11 }
12};
13
14const LoginButton: React.FC = () => {
15 const { loginWithRedirect } = useAuth0();
16 return <button onClick={() => loginWithRedirect()}>Log In</button>;
17};
18
19const LogoutButton: React.FC = () => {
20 const { logout } = useAuth0();
21 return (
22 <button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}>
23 Log Out
24 </button>
25 );
26};
27
28const Profile: React.FC = () => {
29 const { user, isAuthenticated, isLoading } = useAuth0();
30
31 if (isLoading) {
32 return <div>Loading ...</div>;
33 }
34
35 return (
36 isAuthenticated && user ? (
37 <div>
38 <img src={user.picture} alt={user.name} />
39 <h2>{user.name}</h2>
40 <p>{user.email}</p>
41 </div>
42 ) : null
43 );
44};
45
46const App: React.FC = () => {
47 const { isAuthenticated } = useAuth0();
48
49 return (
50 <div>
51 {!isAuthenticated ? <LoginButton /> : (
52 <>
53 <LogoutButton />
54 <Profile />
55 </>
56 )}
57 </div>
58 );
59};
60
61const root = createRoot(document.getElementById('root')!);
62
63root.render(
64 <Auth0Provider {...providerConfig}>
65 <App />
66 </Auth0Provider>
67);