Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
Input wont reset after form submission?

I am using email.js to send emails client side, and validator to validate the email and phone number. Everything works fine, except... I am trying to empty the input fields after a successful submission.

Here is what I have so far:

State management:

    const formRef = useRef()
    const [emailError, setEmailError] = useState('')
    const [phoneError, setPhoneError] = useState('')


    const [inputValues, setInputValues] = useState({email: "", phone: ""})
    const handleOnChange = event => {
        const { name, value } = event.target;
        setInputValues({ ...inputValues, [name]: value });
        validateEmail(inputValues.email)
        validatePhone(inputValues.phone)
    };

Validation and Submit handler:

    const validateEmail = (email) => {
        if (validator.isEmail(email)) {
            setEmailError('Valid Email :)')
            return true
        } else {
            setEmailError('Enter valid Email!')
             return false
        }
       
    }
    const validatePhone = (phone) => {
        if (validator.isMobilePhone(phone)) {
            setPhoneError('Valid Phone :)')
            return true
        } else {
            setPhoneError('Enter valid Phone!')
            return false
        }
    }

    const handleSubmit = (e) => {
        e.preventDefault()

        const isValidEmail = validateEmail(e.target.email.value)
        const isValidPhone = validatePhone(e.target.phone.value)

        if(isValidEmail && isValidPhone){
            console.log("if both inputs are true, on to submit")

            setSentMessage(false)
       
            //shouldnt this line empty out the current fields?
            setInputValues({email: "", phone: ""})
        } else {
            console.log("one of the inputs is false, wont submit")
        }
    }

Form:

<form ref={formRef} onSubmit={handleSubmit} className={classes.contactPageInputs}>

                <input placeholder='email' type="text" id="userEmail" name="email" onChange={(e) => handleOnChange(e)}></input>
                    <span style={{fontWeight: 'bold', color: 'red' }}>{emailError}</span>
                <input placeholder='phone' id="userPhone" name="phone" onChange={(e) => handleOnChange(e)}></input> <br />
                    <span style={{fontWeight: 'bold', color: 'red' }}>{phoneError}</span>
                <button className={classes.submitButton}>submit</button>
</form>

QUESTION: How can I reset the input fields after submission?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Setting the form refs value to null worked. Here is what I added to the handleSubmit function, after sending the email:

formRef.current[0].value = null
formRef.current[1].value = null

UPDATE This si the better way. I added value={inputValues.user_email}, value={inputValues.user_phone}, value={inputValues.user_message} to each respective input field.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda