본문 바로가기

클라이언트/React
[리액트(React)] react-hook-form

// react-hook-form

- form을 쉽게 조작할 수 있도록 도와주는 React 라이브러리

- 코드를 간결하게 유지할 수 있다.

- 불필요한 리렌더링을 줄일 수 있고, validation 체크가 용이하다.


1. 설치

npm install react-hook-form

2. 사용

import { useForm } from 'react-hook-form';

const { register, handleSubmit, formState: { errors }, setError, setValue } = useForm<타입>();
const onValid = (data: 타입) => {
  if(조건) {
    setError('식별자', { message : '메시지' })
  }
};

<form onSubmit={handleSubmit(onValid)}>
  <input {...register('식별자'), {옵션}}/>
  <button></button>
</form>
  • register : 입력 필드(input)을 form에 등록하고 유효성 검사를 해주는 함수

  • handleSubmit : form의 onSubmit 이벤트를 처리하는 함수
    - onValid : 데이터가 유효할 때 호출하는 함수 (필수)
    - onInvalid : 데이터가 유효하지 않을 때 호출하는 함수

  • 옵션: required, minLength, maxLength등 유효성 규칙을 추가할 수 있다.
    - value, message로 나누어서 error message도 전달할 수 있다.
    - pattern으로 정규식을 유효성 규칙으로 추가할 수도 있다.

  • formState : error message 등 error 정보를 받을 수 있다.

  • setError : error를 발생시킬 수 있다.
    - shouldFocus 속성을 true로 하여 focus를 줄 수 있다.

  • setValue : 특정 필드의 값을 프로그래밍적으로 설정할 수 있다.

import { useForm } from 'react-hook-form';
import { useSetRecoilState } from 'recoil';
import { toDoState } from './atoms';

interface IForm {
  toDo: string;
}

function CreateToDo() {
  const setToDos = useSetRecoilState(toDoState);
  const { register, handleSubmit, setValue } = useForm<IForm>();
  const handleValid = ({ toDo }: IForm) => {
    setToDos((oldToDos) => [
      ...oldToDos,
      {
        text: toDo,
        id: Date.now(),
        category: 'TO_DO',
      },
    ]);
    setValue('toDo', '');
  };

  return (
    <form onSubmit={handleSubmit(handleValid)}>
      <input
        {...register('toDo', {
          required: 'ToDo is required',
          maxLength: {
            value: 100,
            message: 'Todo should be shorter than 100',
          },
        })}
        placeholder="Write a to do"
      />
      <button>Add</button>
    </form>
  );
}

export default CreateToDo;