Home > other >  Login still happens even when input fields are empty
Login still happens even when input fields are empty

Time:03-07

I am creating a login page using React. Localhost:3000 still alerts 'thank you for registering' even when inputs are empty. Did this from tutorial and followed the codes exactly, but still can't figure out for days. I tried removing the space between the double quotes in the if-else statement, but to no avail.

Here's the code:

import { useState } from "react";
import styles from "./register.css";
import Login from "../../containers/login/index";

function Register({ props, history }) {

    const [name, setName] = useState();
    const [email, setEmail] = useState();
    const [password, setPassword] = useState();

    function registerClicked() {
        if (name !== " " && email !== " " && password !== " ") {
            console.log(name, email, password);
            alert("Thanks for registering");
            history.push("/");
        } else {
            alert("Please register to continue");
        }
    }


    return(
        <div className="regContainer">

            <p className="registerTitle">Register to sign in</p>

            <input type="text" 
            placeholder="Create username" 
            onChange={(nameText) => setName(nameText.target.value)} />

            <input type="text" 
            placeholder="Email address" 
            onChange={(emailText) => setEmail(emailText.target.value)} />

            <input type="password" 
            placeholder="Password" 
            onChange={(passwordText) => setPassword(passwordText.target.value)} />

            <button onClick={() => registerClicked()}>Register</button>

            <p className="loginInstead">Already have an account? Sign in instead</p>

        </div>
    );
}

export default Register;

CodePudding user response:

cause const [name, setName] = useState(); the name actually equals undefined.

set a default value const [name, setName] = useState("");

or use a fuzzy judgement if(!name)

CodePudding user response:

All states after registering must be set to null

if (name !== "" && email !== "" && password !== "") {
        console.log(name, email, password);
        alert("Thanks for registering");
        setName(null);
        setEmail(null);
        setPassword(null);
        history.push("/");
    }

prop value must be set to all inputs

 <input type="text" 
        placeholder="Create username" 
        value={name}
        onChange={(nameText) => setName(nameText.target.value)} />

        <input type="text" 
        placeholder="Email address"
        value={email} 
        onChange={(emailText) => setEmail(emailText.target.value)} />

        <input type="password" 
        placeholder="Password" 
        value={password}
        onChange={(passwordText) => setPassword(passwordText.target.value)} />
  • Related