본문 바로가기

Frontend/React

[React] react-hook-form 사용법(useForm, watch)

728x90
프로젝트 진행 중 로그인, 회원가입 기능을 구현하면서
react-hook-form이라는 편리한 API를 찾게 되어서 간단한 사용법을 기록하려고 한다.

 

  • react-hook-form은 여러 개의 input 태그를 효율적으로 관리할 수 있는 기능이다.
  • 공식 문서에서 내가 필요한 기능만 간단히 공부하고 하는 기록이다.

시작하기

  1. 먼저 npm이나 yarn에서 react-hook-form을 install 해준다.
  2. react-hook-form에서 useForm을 import 해준다.
import { useForm } from "react-hook-form";
export default function App() {
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch
  } = useForm();
  return (
    <div>
      <form>
        <p>id</p>
        <input />
        <p>password</p>
        <input />
        <p>phone</p>
        <input />
        <button type="submit"/>
      </form>
    </div>
  );
}

  • 간단한 form을 구현했다.
  • useForm( ) 함수의 반환값에서 필요한 기능들을 가져왔다.

register

  • register은 관리하고자 하는 input을 추가하고, 관리하고 싶은 기능들을 추가하는 중심적인 기능을 한다.
register( name, [option(validation)])
  • register의 첫 번째 인자로 name을 받는데 이는 input의 이름이 된다. key의 기능을 하는 것이다.
  • 두 번째 인자는 옵션으로, 유효성을 검사할 수 있는 기능이다.
    • required, maxLength, minLength 등 html에서 지원하는 유효성 검사가 가능하다.
    • pattern 속성을 통해 정규식으로 유효성 검사도 가능하다.
    • validate 속성으로 callback 함수를 전달해 유효성 검사도 가능하다.
  • 유효성 검사에서 통과하지 못 했다면 message 프로퍼티로 에러 메세지를 설정할 수 있다.

handleSubmit

  • handleSubmit은 form 태그의 onSubmit 메서드 콜백 함수이다.
handleSubmit(SubmitHandler,[SubmitErrorHandler])
  • 첫 번째 인자는 form의 input들의 data를 다루는 콜백 함수다.
    • {key(name) : value} 형식으로 모든 data들이 포함된 객체를 인자로 받는다.

  • 인자로 받은 data 객체를 콘솔에 출력한 모습이다.

errors

  • errors는 앞서 언급한 register의 유효성 검사에서 일어난 에러들을 다루는 객체이다.
  • handleSubmit의 두 번째 인자인 에러를 처리하는 함수에서 form의 에러들을 다룰 수 있다.
import { useForm } from "react-hook-form";
export default function App() {
  const {		
    register,
    handleSubmit,
    formState: { errors },
    watch
  } = useForm();
  const onValid = (data) => {			//submit이 정상적으로 되었을 때 data를 다루는 함수
    console.log(data);
  };
  const onInvalid = (error) => {		//유효성 검사에 실패했을 때 errors를 다루는 함수
    console.log(error);
  };
  return (
    <div>
      <form onSubmit={handleSubmit(onValid, onInvalid)}>
        <p>id</p>
        <input
          {...register("id", {
            minLength: {
              value: 4,
              message: "4자 이상 입력해주세요"
            }
          })}
        />
        <p>password</p>
        <input
          {...register("password", {
            maxLength: {
              value: 12,
              message: "12자 이하로 입력해주세요"
            }
          })}
        />
        <p>phone</p>
        <input {...register("phone")} />
        <button type="submit">submit</button>
      </form>
    </div>
  );
}
  • form에서 id와 password의 유효성 검사에 실패했을 때 에러 객체는 어떤 모습일까?

  • input의 name을 key값으로 한 에러 객체에 type, message, ref를 담고 있다.
  • 즉, 한 input에서 여러 에러가 발생해도 type을 통해 에러를 구분할 수 있다.
{errors.id && <p>{errors.id.message}</p>}
  • input 아래에 위와 같은 코드를 추가하여 에러 객체가 있을 때 그 message를 띄워줄 수 있다.

  • type을 통해 다른 message를 띄워줄 수 있으니 정말 편한 기능이다.

watch

  • 마지막으로 다룰 watch 프로퍼티는 input 데이터들을 submit 전에 다룰 수 있는 기능이다.
  • watch에 대한 공식 문서에서 자세한 설명을 볼 수 있다.
  • 지금 다룰 기능은 모든 input data를 다룰 수 있는 콜백 함수를 호출하고, 해당 함수에 대한 cleanup 함수를 리턴하는 기능이다.
import { useEffect } from "react";
import { useForm } from "react-hook-form";
export default function App() {
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch
  } = useForm();

  useEffect(() => {
    const subscirbe = watch((data, { name }) => console.log(data, name));
    //모든 input 데이터를 담은 객체 data, change 이벤트가 발생하고 있는 input의 name을 인자로 받는 콜백함수
    return () => subscirbe.unsubscribe();
  }, [watch]);

  return (
    <div>
      <form>
        <p>id</p>
        <input {...register("id")} />
        <p>password</p>
        <input {...register("password")} />
        <p>phone</p>
        <input {...register("phone")} />
        <button type="submit">submit</button>
      </form>
    </div>
  );
}
  • 각각의 input에 입력할 때마다 콘솔은 어떤 모습일까

  • 위처럼 모든 input의 datachange 이벤트가 발생하고 있는 input의 name이 출력된 것을 볼 수 있다.
728x90