Home > OS >  fullname,email,password,setError,setError,fullname,error is not defined react js
fullname,email,password,setError,setError,fullname,error is not defined react js

Time:02-27

As you can see I am trying to apply validation to registration form that is, when user enters values in input fields he should be able to see the validations. Can anyone tell me where i am going wrong here. I am using functional components and the form should validate before submitting.

    import React, {useState, useRef, useEffect} from 'react';
    
    const Home = () => {
    
    const [ userRegistration, setUserRegistration ] = useState ({
        fullname:"", email:"", phone:"", password:""
    });
    
    
    // States for checking the errors
    const [submitted, setSubmitted] = useState(false);
    
    
    const [record, setRecord] = useState ([]);
    
       const handleInput = (e) => {
        setUserRegistration ({...userRegistration, [e.target.name] : e.target.value});
        setSubmitted(false);
    }

Here I am struggling

    // Handling the form submission
    const handleSubmit = (e) => {
        e.preventDefault();
        // const newRecord = {...userRegistration, id: new Date().getTime().toString()};
        //    setRecord = {...record, newRecord};
        //    setUserRegistration ({fullname:"", email: "", phone:"", password:""});
           {
        if (fullname === '' || email === '' || password === '') {
          setError(true);
        } else {
          setSubmitted(true);
          setError(false);
        }
      };
    }
      // Showing success message
      const successMessage = () => {
        return (
          <div
            className="success"
            style={{
              display: submitted ? '' : 'none',
            }}>
            <h1>User {fullname} successfully registered!!</h1>
          </div>
        );
      };
     
      // Showing error message if error is true
      const errorMessage = () => {
        return (
          <div
            className="error"
            style={{
              display: error ? '' : 'none',
            }}>
            <h1>Please enter all the fields</h1>
          </div>
        );
      };
      
    
    //    const handleSubmit = (e) => {
    //        e.preventDefault();
    //        const newRecord = {...userRegistration, id: new Date().getTime().toString()};
    //        setRecord = {...record, newRecord};
    //        setUserRegistration ({fullname:"", email: "", phone:"", password:""});
    //    }
     
     
        return (
            <>
            {/* Calling to the methods */}
          <div className="messages">
            {errorMessage()}
            {successMessage()}
          </div>
            <form>
                                     <div>
                                     <label htmlFor="fullname">Fullname</label>
                                     <input type="text" autocomplete="off" onChange={handleInput} value={userRegistration.fullname} name="fullname" id="fullname" />
                                     </div>
                                     <div>
                                     <label htmlFor="email">email</label>
                                     <input type="text" autocomplete="off" onChange={handleInput} value={userRegistration.email} name="fullname" id="fullname" />
                                     </div>
                                     <div>
                                     <label htmlFor="phone">phone</label>
                                     <input type="text" autocomplete="off" onChange={handleInput} value={userRegistration.phone} name="fullname" id="fullname" />
                                     </div>
                                     <div>
                                     <label htmlFor="password">password</label>
                                     <input type="text" autocomplete="off" onChange={handleInput} value={userRegistration.password} name="fullname" id="fullname" />
                                     </div>
                                     <button onClick={handleSubmit}>SUBMIT</button>
            </form>
            <div>
                {
                record.map ((curElem) => {
                    const {id, fullname, email, phone, password} =curElem
                      return(
                               <div key={id} >
                                   <p>{fullname}</p>
                                   <p>{email}</p>
                                   <p>{phone}</p>
                                   <p>{password}</p>
                               </div>
                      )
                }
                )
                }
             </div>
            </>
        )}
    export default Home;

The error is:

src\component\Home.js

Line 31:9:   'fullname' is not defined  no-undef

  Line 31:28:  'email' is not defined     no-undef

  Line 31:44:  'password' is not defined  no-undef

  Line 32:7:   'setError' is not defined  no-undef

  Line 35:7:   'setError' is not defined  no-undef

  Line 47:19:  'fullname' is not defined  no-undef

  Line 58:20:  'error' is not defined     no-undef

CodePudding user response:

  1. You havent added state variable for error. (error variable is used in errorMessage function definition)
  1. in successMessage function definition you have to give {userRegistration.fullname} instead of {fullname}
  2. In handleSubmit you are using fullname, email, password but they are not destructured from userRegistration. So you have to give either userRegistration.fullname, etc. like mentioned in 2. or destructure the properties from the userRegistration object before the if condition like const {fullname,email,password} = userRegistration;
  3. All the inputs are having same 'name' attribute, change to the respective key for it to work correctly.

CodePudding user response:

There are quite a few adjustments that you need to make.

  1. You do not have Error handling useState. You setError state, but you do not have it initiated at the top of the Home component.
  2. From the beginning, you set setSubmitted to false, so unless you change that state to 'true', you do not need to set it to false since it is already false.
  3. Your Submit function receives data on onSubmit event that you should JSON.stringify in order to use it further, but you just change states in your function. Or you can push that form data into the state too.
  4. Your validation is super duper basic just checking if it is an empty string. I would suggest writing up more validations than that.
  5. In successMessage function definition you have to give {userRegistration.fullname} instead of {fullname} .
  6. Your input names are literally the same for all inputs. They must be different, just like "id"s. Your ids are also the same. Your form object keys will be named after "name" of each input field. Change that.
  7. Lastly, use either Formik or Yup or React Hook Form that will assist you tremendously with this process and make it smoother and simplier. For example, read documentation on React Hook Form here(it is quite easy documentation)

https://react-hook-form.com/

  • Related