how to make react-hook-form work with multiple forms in one page?

webcoder picture webcoder · Feb 18, 2020 · Viewed 12k times · Source

I am using react-hook-form in my project and I have 2 totally separate forms, but when I submit one of the forms and if some fields in the other form is required I can't submit the current form, check the demo, and try to submit one of the form, the forms should work independently of each other but it looks like they depend on each other.

any help please?

Answer

Faizaan Khan picture Faizaan Khan · Feb 18, 2020

Welcome to StackOverflow @webcoder You are using the same hook instance for both forms. You will have to reuse with different names.

import React from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

import "./styles.css";

function App() {
  const { register, errors, handleSubmit } = useForm({
    mode: "onBlur"
  });

  const {
    register: register2,
    errors: errors2,
    handleSubmit: handleSubmit2
  } = useForm({
    mode: "onBlur"
  });

  const onSubmit = data => {
    alert(JSON.stringify(data));
  };

  const onSubmitEmail = data => {
    alert(JSON.stringify(data));
  };

  return (
    <div className="App">
      <form key={1} onSubmit={handleSubmit(onSubmit)}>
        <div>
          <label htmlFor="firstName">First Name</label>
          <input
            name="firstName"
            placeholder="bill"
            ref={register({ required: true })}
          />
          {errors.firstName && <p>This is required</p>}
        </div>

        <div>
          <label htmlFor="lastName">Last Name</label>
          <input
            name="lastName"
            placeholder="luo"
            ref={register({ required: true })}
          />
          {errors.lastName && <p>This is required</p>}
        </div>
        <input type="submit" />
      </form>

      <form key={2} onSubmit={handleSubmit2(onSubmitEmail)}>
        <div>
          <label htmlFor="email" placeholder="[email protected]">
            Email
          </label>
          <input name="email" ref={register2({ required: true })} />
          {errors2.email && <p>This is required</p>}
        </div>
        <input type="submit" />
      </form>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);