포스코x코딩온 웹 풀스택 양성과정

[포스코x코딩온] 웹 풀스택 과정 13주차 회고 | React Hook Form

Codult 2024. 4. 5. 15:15
728x90

 

📌 React Hook Form

리액트에서 폼을 쉽게 관리할 수 있도록 도와준다.
폼의 상태 관리와 유효성 검사를 간단하게 다룰 수 있다.

💡 설치

npm i react-hook-form

💡 주요 키워드

  • register: 입력요소에 연결하기 위한 함수로, 입력요소에서 유효성 검사를 설정할 수 있다.
<input type="text"
  {...register("username", {
    required: "이름을 입력하세요",
    minLength: {message: "최소 두글자 이상 작성하세요", value: 2}
  })}
/>
  • handleSubmit: 폼의 제출을 처리하기 위한 함수로, 두개의 함수를 인자로 받을 수 있다. (하나는 유효할 때 실행되는 함수이며 필수, 나머지는 유효하지 않을 때 실행되는 함수이며 선택)
<form onSubmit={handlSubmit(onValid)}>
</form>
  • watch: 특정 폼 필드의 값을 실시간으로 관찰하는 함수이다.
  • formState: 폼의 상태를 나타내는 객체로, erros, isValid, isDirty, isSubmitted 등의 상태를 확인할 수 있다.

💡 예시

// 1. useForm을 import 한다.
import { useForm } from 'react-hook-form';

// 2. 사용할 함수(register, handleSubmit, watch, formState 등)를 가져온다.
export default function Form() {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm();
}

// 3. handleSubmit에서 유효할 때 실행할 함수를 정의한다.
const onValid = (data) => {console.log(data);}

// 4. 폼 설정
return (
  <>
    <form onSubmit={handleSubmit(onValid)}>
      <input type="text"
        {...register("username", {
          required: "이름을 입력하세요",
          minLength: { message: "최소 두글자 이상 작성하세요.", value: 2 }
        })}
        placeholder="username"
      />
      {errors.username?.message} // errors.username이 있다면 errors.username.message를 보여줌
      <br />
      <input type = "text"
        {...register("email", {
          required: "이메일을 입력하세요",
          validate: {
            useGmail: (value) => {
              return (
                value.includes("gmail.com")||"gmail로만 가입 가능합니다."
              );
            },
          },
        })}
        placeholder="email"
      />
      <br />
      <button type="submit">Submit</button>
    </form>
  </>
)
728x90