Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
Resetting React Form values after validation

have that problem with resetting the values of the input fields in the form. and wanted to ask if somebody knows a better and way to do that instead of just making 'useState' for every field...

    const handleSubmit = (e) => {
        e.preventDefault();
        
        emailjs.sendForm('sample_id', 'someother_id', formRef.current, 'user_is')
        .then((result) => {
            console.log(result.text);
        }, (error) => {
            console.log(error.text);
        });

        setMessage(true);
        setEmail("");
        setName("");
        setSubject("");
        setTextarea("");
    };

    return (
        <div className="contact" id="contact">
            <div className="left">
                <img src="" alt="" />
            </div>
            <div className="right">
                <h2>Kontakt</h2>
                <form ref={formRef} onSubmit={handleSubmit}>
                    <label>Name</label>
                    <input onChange={(e) => setName(e.target.value)} type="text" placeholder="Name" name="user_name" value={name} />
                    <label>Email</label>
                    <input onChange={(e) => setEmail(e.target.value)} type="email" placeholder="Email" name="user_email" value={email} />
                    <label>Betreff</label>
                    <input onChange={(e) => setSubject(e.target.value)} type="text" placeholder="Subject" name="user_subject" value={subject} />
                    <label>Nachricht</label>
                    <textarea onChange={(e) => setTextarea(e.target.value)} placeholder="Message" name="message" value={textarea} />
                    <button type="submit">Send</button>
                    {message && <span>Thanks we will respond ASAP.</span>}
                </form>
            </div>
        </div>
    )
}

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could use a single state for all the form values (kinda like we did before functional components)

// this could be outside your component
const initialState = { email: "", name: "", subject: "", textArea: ""};
// declaring your state
const [formState, setFormState] = React.useState(initialState);

and then

    const handleSubmit = (e) => {
    e.preventDefault();
    
    emailjs.sendForm('sample_id', 'someother_id', formRef.current, 'user_is')
    .then((result) => {
        console.log(result.text);
    }, (error) => {
        console.log(error.text);
    });

    setMessage(true);
    setFormState(initialState)
};

You also would have to rewrite your input handlers. Like that :

<input onChange={(e) => setFormState({...formState, name: e.target.value})} type="text" placeholder="Name" name="user_name" value={name} />
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda