Resetting React Form values after validation

1k Views Asked by At

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>
    )
}

1

There are 1 best solutions below

2
Hugo F. On

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} />