The useEffect function will be called when the DOM is ready. The function first checks to see if loading is true. Loading will be false if the user has logged in.
Next, the useAuthState function is called to get the current user state. The user state is used to construct the HTML for the login form.
The useNavigate function will be called when the user clicks on either of the login buttons. The function first sets the state of the buttons to login and google, respectively. Then, the function calls signInWithEmailAndPassword with the user's email address and password.
Library: react
import "./Login.css";
import { Link, useNavigate } from "react-router-dom";
import { useAuthState } from "react-firebase-hooks/auth";
import React, { useEffect, useState } from "react";
import { auth, signInWithEmailAndPassword, signInWithGoogle } from "./firebase";
function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [user, loading, error] = useAuthState(auth);
const navigate = useNavigate();
useEffect(() => {
if (loading) {
// maybe trigger a loading screen
return;
}
if (user) navigate("/dashboard");
}, [user, loading]);
return (
<div className="login">
<div className="login__container">
<input
type="text"
className="login__textBox"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="E-mail Address"
/>
<input
type="password"
className="login__textBox"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
/>
<button
className="login__btn"
onClick={() => signInWithEmailAndPassword(email, password)}
>
Login
</button>
<button className="login__btn login__google" onClick={signInWithGoogle}>
Login with Google
</button>
<div>
<Link to="/reset">Forgot Password</Link>
</div>
<div>
Don't have an account? <Link to="/register">Register</Link> now.
</div>
</div>
</div>
);
}
export default Login;