TIL no.51 - react-hook-form

김종진·2021년 4월 10일
1

React

목록 보기
11/17

react-hook-form

이번 기업 협업 프로젝트를 진행 중 무수한 Input태그의 Form을 구현하는 중 아주 유용한 라이브러리를 알게 되었다.

웹 사이트의 필수 기능 로그인/회원가입 페이지를 구현하다 보면 Input / Form을 다루는 것을 필수인데 보다 많은 Input태그가 있는 양식을 구현하고 Form을 관리하는 것은 상당히 까다로운데 react-hook-form 이를 손쉽게 도와주는 매우 좋은 라이브러리이다.

  • Hooks API이다.
  • 렌더링 최소화
  • 타입스크립트로 작성된 프로젝트라서 타입스크립트와 아주 잘 맞는다.
  • 공식 문서가 너무나 잘 되어있다.

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

설치

npm install react-hook-form

  1. Input 값 가져오기
import { useForm } from "react-hook-form";
const { register, handleSubmit } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

return (
<form className="flex justify-between" onSubmit={handleSubmit(onSubmit)}>
  <div>
    <input
     name="id"
     type="text"
     className="border-gray-300 rounded h-8 px-2 text-xs mr-6"
     ref={register}
    />

    <input
     name="password"
     type="password"
     className="border-gray-300 rounded h-8 px-2 text-xs"
     ref={register}
    />
  </div>
  <Button type="submit" name="조회" />
</form>
);

해당 코드를 보면ref={register} 사용한다. react-hook-form 에서는 각 input 태그에 ref={register}만 넣어주면 해당 값을 바로 가져올수 있다.

form submit시 새로고침을 막는 e.preventDefault()를 작성하지 않아도 된다.

  1. 유효성 검사
(...)
import { useForm } from "react-hook-form";
import "./styles.css";

function App() {
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm();

  const onSubmit = (data) => {
    alert(JSON.stringify(data));
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>Name</label>
      <input
        {...register("Name", {
          required: true,
          maxLength: 10,
          pattern: /^[A-Za-z]+$/i
        })}
      />
      {errors?.Name?.type === "required" && <p>This field is required</p>}
      {errors?.Name?.type === "maxLength" && (
        <p>Name은 10자를 초과할 수 없습니다.</p>
      )}
      {errors?.Name?.type === "pattern" && (
        <p>영문명으로 작성 부탁드리겠습니다.</p>
      )}

      <label>Age</label>
      <input {...register("age", { min: 18, max: 99 })} />
      {errors.age && (
        <p>18세 이상 99이하만 가능합니다.</p>
      )}
      <input type="submit" />
    </form>
  );
}

유효성 검사도 아주 간단하고 강력하다..!
input 태그안에 required만 작성해줘도 값을 입력하지 않은 input 태그를 바로 찾아 알려준다.

이외에도 내용의 길이, 최소값, 최대값, 정규표현식도 동일한 방식으로 쉽게 적용이 가능하다.
reValidateMode을 사용하면 언제 유효성 검사를 할지도 정할 수 있다.

formState: { errors } 기능을 더하면 유효성에 어긋났을 때 조건부 렌더링을 통해 무엇이 어떻게 잘못 작성되었는지 각각 맞게 내용을 전달할 수 있다!

이외에도 다양한 기능을 제공하며 공식문서에 정리가 상당히 잘 되어 있다.

복잡한 Form을 다루고자 할때 react-hook-form을 사용한다면 보다 우수한 성능으로 효율적으로 관리할 수 있을 듯 하다! 정말 매우 추천한다!

profile
FE Developer

0개의 댓글