Skip to content
React Hook프로젝트

Testing React Hook Form with Next.js

1 min readProjectsMoved from my Tistory blogRead the Korean original

At work and in personal projects, I often stored the values of the inputs inside a form in state, and handled the related exceptions and errors with really long code. I think I can now handle this simply with React Hook Form.

Besides the useForm options I used below, there are many more useful features.

https://react-hook-form.com/docs/useform

useForm

tsx
import { FieldErrors, useForm } from "react-hook-form";

interface LoginForm {
  userName: string;
  email: string;
  password: string;
  errors?: string;
}

function Forms() {
  const {
    register,
    watch,
    handleSubmit,
    formState: { errors },
    setValue,
    setError,
    reset,
    resetField,
  } = useForm<LoginForm>({
    mode: "onChange",
  });

  const onValid = (data: LoginForm) => {
    // Runs when every input in the form is filled in correctly
    console.log("I'am Valid");
    // setError('userName',{message:'이미 존재하는 계정'}) <-- duplicate ID error handling
  };
  const onInvalid = (errors: FieldErrors) => {
    // Runs when even one input in the form isn't filled in correctly
    console.log(errors);
    reset(); // If invalid, you can reset every input
  };

  return (
    <form
      className="flex flex-col gap-2 px-2 mt-2"
      onSubmit={handleSubmit(onValid, onInvalid)}
    >
      <input
        {...register("userName", {
          required: "UserName is required",
          minLength: {
            message: "The UserName should be longer than 5 chars.",
            value: 5,
          },
        })}
        type="text"
        placeholder="User Name"
        className={`${errors.userName ? "border-red-500" : ""}`}
      />
      <span className="text-red-500">{errors.userName?.message}</span>
      <input
        {...register("email", {
          required: "Email is required",
          validate: {
            notGmail: (value) =>
              !value.includes("gmail.com") || "Gmail is not allowed",
          },
        })}
        type="email"
        placeholder="Email"
      />
      <span className="text-red-500">{errors.email?.message}</span>
      <input
        {...register("password", { required: "Password is required" })}
        type="password"
        placeholder="Password"
      />
      <span className="text-red-500">{errors.password?.message}</span>
      <input
        className="w-full bg-blue-500 py-2 text-white"
        type="submit"
        value="Create"
      />
    </form>
  );
}

export default Forms;
The result
Figure 1. The result
  • #React Hook Form
  • #Simple form management
  • #Frontend Developer Sungjun Um

More in Projects