Estoy usando email.js para enviar correos electrónicos del lado del cliente y validador para validar el correo electrónico y el número de teléfono. Todo funciona bien, excepto... Estoy tratando de vaciar los campos de entrada después de un envío exitoso.
Esto es lo que tengo hasta ahora:
Administración del Estado:
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) };Controlador de validación y envío:
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") } }Forma:
<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>PREGUNTA: ¿Cómo puedo restablecer los campos de entrada después del envío?
Establecer el valor de las referencias del formulario en nulo funcionó. Esto es lo que agregué a la función handleSubmit , después de enviar el correo electrónico:
formRef.current[0].value = null formRef.current[1].value = null ACTUALIZAR Esta es la mejor manera. value={inputValues.user_email}, value={inputValues.user_phone}, value={inputValues.user_message} a cada campo de entrada respectivo.