Home > OS >  React Hook Form: How to reset the form content after submission
React Hook Form: How to reset the form content after submission

Time:09-17

I have a hidden field when you clicked the YES option, I want to reset the form to hide again the field after successful submission.

Below is my code and here is the link to sandbox.

import { React, useState } from "react";
import emailjs from "emailjs-com";
import { useForm } from "react-hook-form";

const NameForm = () => {
  const [showYes, setShowYes] = useState(false);
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors }
  } = useForm({
    defaultValues: { yes_no: false, yes_i_understand: false }
  });
  const sendEmail = formData => {
    emailjs
      .send("YOUR_SERVICE_ID", "YOUR_TEMPLATE_ID", formData, "YOUR_USER_ID")
      .then(
        result => {
          console.log(result.text);
        },
        error => {
          console.log(error.text);
        }
      );
    reset();
  };

  return (
    <div>
      <h1 className="text-center text-md-left mb-3">Get in Touch</h1>
      <p>Have you spoken to a us in the last 14 days?</p>
      <form className="contact-form" onSubmit={handleSubmit(sendEmail)}>
        <div className="mb-2">
          <div className="form-check form-check-inline">
            <input
              className="form-check-input"
              type="radio"
              value="Yes"
              id="yes"
              name="yes_no"
              onClick={setShowYes}
            />
            <label className="form-check-label mr-4" htmlFor="yes">
              Yes
            </label>
          </div>
          <div className="form-check form-check-inline">
            <input
              className="form-check-input"
              type="radio"
              value="No"
              id="no"
              name="yes_no"
              defaultChecked
              onClick={() => setShowYes(false)}
            />
            <label className="form-check-label mr-4" htmlFor="no">
              No
            </label>
          </div>
        </div>
        {showYes && (
          <div className="form-group row mb-0">
            <div className="col-12 py-3">
              <input
                type="text"
                className="form-control custom--fields-mod text-the-primary"
                id="agentName"
                placeholder="Agent Name *"
                name="agent_name"
                {...register("agent_name", { required: true })}
              />
              {errors.agent_name && (
                <span className="invalid-feedback d-block">
                  Please fill out this field.
                </span>
              )}
            </div>
          </div>
        )}
        <div className="form-group mb-0 py-3">
          <textarea
            className="form-control custom--fields-mod text-the-primary"
            id="message"
            rows="3"
            placeholder="Message *"
            name="message"
            {...register("message", { required: true })}
          ></textarea>
          {errors.message && (
            <span className="invalid-feedback d-block">
              Please fill out this field.
            </span>
          )}
        </div>
        <div className="form-group row py-2 mb-0">
          <div className="col-12 text-center text-md-left py-2 py-md-0">
            <input
              className="buttons-width float-md-right btn btn-dark-moderate-orange rounded-0"
              type="submit"
              value="SEND MESSAGE"
            />
          </div>
        </div>
      </form>
    </div>
  );
};
export default NameForm;

I'm not sure if I missed something on passing the data to the form. I also put defaultChecked attribute in option NO.

CodePudding user response:

The 'showYes' state should be reset to false after submission.

I updated some codes. https://codesandbox.io/s/react-hook-form-using-emailjs-2-forked-fmido?file=/src/App.js

const resetForm = () => {
  reset();
  setShowYes(false);
};
const sendEmail = (formData) => {
  emailjs
    .send("YOUR_SERVICE_ID", "YOUR_TEMPLATE_ID", formData, "YOUR_USER_ID")
    .then((result) => {
      console.log(result.text);
      resetForm();
    },
    (error) => {
      console.log(error.text);
    }
  );
};

I'm not sure if I missed something on passing the data to the form. I also put defaultChecked attribute in option NO.

<input
  className="form-check-input"
  type="radio"
  value="true"
  id="yes"
  name="yes_no"
  {...register("yes_no", { required: true })}
  onClick={setShowYes}
/>
<label className="form-check-label mr-4" htmlFor="yes">
  Yes
</label>
  • Related