티스토리 뷰

React에서 form의 validation을 도와주는 라이브러리이다.

이 라이브러리는 기본적으로 uncontrolled component를 베이스로 하지만 controlled component에 대한 지원도 하고 있다.

react hook form의 장점은 가볍고, 다른 디펜던시가 없으며, ref를 기반으로 하여 다른 UI 라이브러리와 호환이 잘된다는 것이다.

가장 간단한 형태

const { register, handleSubmit } = useForm();

여기서 register는 해당 컴포넌트의 값을 트래킹하고 validation을 하기위해 react hook form 라이브러리에 등록한다는 뜻이다. input을 등록하려면 아래처럼 ref에 register을 넘겨주면 된다. 이 때 중요한 점은 반드시 name 필드를 넘겨줘야 하며, 이는 유니크해야된다는 것이다.

<input type="text" ref={register} name="firstName" />

handleSubmit 메서드는 form 제출을 핸들링하는 메서드이며, form 컴포넌트의 onSubmit prop에 넘겨주면 된다.

const onFormSubmit = data => console.log(data);
const onErrors = errors => console.error(errors);

<form onSubmit={handleSubmit(onFormSubmit, onErrors)}>
    {/* ... */}
</form>

handleSubmit은 두가지 아규먼트를 받는데, 첫번째는 폼 validation이 success일 때 호출하는 콜백이고 두번째는 폼 validation이 fail일 때 에러와 함께 호출되는 콜백이다.

간단한 example은 아래와 같다.

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

export default function App() {
  const { register, handleSubmit } = useForm();
  const onSubmit = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstName" ref={register} />
      <input name="LastName" ref={register} />            
      <input type="submit" />
    </form>
  );
}

위의 코드를 보면 알겠지만, 기본적으로 ref를 사용하는 uncontrolled 방식이기 때문에 onChange나 value 같은 상태 값을 prop으로 넘겨줄 필요가 없어 코드가 깔끔하다.

Validation과 Error 다루기

validation 옵션은 register 메서드에 아규먼트로 넣어주면 된다. validation option은 아래와 같다.

  • required
  • minLength, maxLength (문자열 길이)
  • min, max (숫자)
  • type (input 필드의 타입. email, number, text 등)
  • pattern (regex)
<Input name="name" innerRef={register({ required: true })} />

위의 코드는 input 컴포넌트를 required하게 한 것인데 만약 아무 값도 입력하지 않고 서브밋하면 handleSubmit 메서드의 두번째 콜백이 실행된다. 그리고 에러 오브젝트는 useForm에서 접근할 수 있다.

const { register, handleSubmit, errors } = useForm();

서드 파티 컴포넌트와 함께 쓰기

material ui 처럼 반드시 controlled component 형태로 사용하는 라이브러리들이 있는데, react hook form은 이런 컴포넌트를 지원한다. 이 경우에는 register 메서드 대신 control 이라는 객체를 사용한다.

const { register, handleSubmit, errors, control } = useForm();

또한 react hook form에서는 Controller 라는 wrapper 컴포넌트를 제공한다. 이 컴포넌트를 통해서 controlled component를 래핑해서 react hook form과 사용할 수 있다.

아래의 예시에서 보면 register을 넘겨주듯이 대신 control을 넘겨주고, as prop으로 사용하고자 하는 controlled component를 내려준다. 그리고 그 컴포넌트의 props는 그대로 Controller에서 전달 가능하다. validation option은 rules prop으로 넘겨주면 된다.

<Controller
  name="role"
  control={control}
  as={Select}
  options={selectOptions}
  defaultValue=""
  rules={{ required: "Role is required" }}
/>

Ref

https://blog.logrocket.com/the-complete-guide-to-react-hook-form/

https://react-hook-form.com/kr/get-started

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함