Mark As Completed Discussion

Implementing Authentication in React

Implementing authentication in a React application involves using a third-party library like Firebase or Auth0. These libraries provide pre-built components and APIs to handle the authentication flow.

For this example, we will use Firebase as our authentication provider.

  1. Install the necessary packages:

    SNIPPET
    1npm install firebase react-firebase-hooks
  2. Import the required modules from Firebase and the useAuthState hook from react-firebase-hooks/auth:

    JAVASCRIPT
    1import React, { useState } from 'react';
    2import firebase from 'firebase/app';
    3import 'firebase/auth';
    4import { useAuthState } from 'react-firebase-hooks/auth';
  3. Initialize Firebase with your project credentials:

    JAVASCRIPT
    1firebase.initializeApp({
    2  apiKey: 'YOUR_API_KEY',
    3  authDomain: 'YOUR_AUTH_DOMAIN',
    4  projectId: 'YOUR_PROJECT_ID',
    5  storageBucket: 'YOUR_STORAGE_BUCKET',
    6  messagingSenderId: 'YOUR_MESSAGING_SENDER_ID'
    7  // ...other configurations
    8});
  4. Create a functional component that handles the authentication process:

    JAVASCRIPT
    1const App = () => {
    2  const [user, loading, error] = useAuthState(firebase.auth());
    3  const [email, setEmail] = useState('');
    4  const [password, setPassword] = useState('');
    5
    6  // Handle sign in
    7  const signIn = async (e) => {
    8    e.preventDefault();
    9    try {
    10      await firebase.auth().signInWithEmailAndPassword(email, password);
    11    } catch (error) {
    12      console.error('Error signing in:', error);
    13    }
    14  };
    15
    16  // Handle sign out
    17  const signOut = async () => {
    18    try {
    19      await firebase.auth().signOut();
    20    } catch (error) {
    21      console.error('Error signing out:', error);
    22    }
    23  };
    24
    25  return (
    26    <div>
    27      {user ? (
    28        <div>
    29          <h2>Welcome, {user.email}!</h2>
    30          <button onClick={signOut}>Sign Out</button>
    31        </div>
    32      ) : (
    33        <div>
    34          <h2>Please sign in:</h2>
    35          <form onSubmit={signIn}>
    36            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" required />
    37            <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" required />
    38            <button type="submit">Sign In</button>
    39          </form>
    40        </div>
    41      )}
    42    </div>
    43  );
    44};
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment