[React] React Hook Form

Tinubee·2023년 1월 2일
0
post-thumbnail

React Hook Form 이란?

React에서 form의 validation을 빠르고 쉽게 도와주는 라이브러리이다. 전체 폼이 리랜더링 되지 않으면서도 각각의 입력값 변화를 관찰할 수 있기에 성능이 뛰어나고, 유연하며 확장가능한 form이다.

1. 설치

npm install react-hook-form

✔︎ react-hook-form 공식홈페이지

2. 사용방법

✅ Register / Watch

✔︎ register : 해당 비제어 컴포넌트의 값을 트래킹하고 유효성 검사 규칙을 Hook에 적용할 수 있다.
✔︎ watch: form의 입력값들의 변화를 관찰 할 수 있게 해주는 함수이다.

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

function Home() {
  const { register, watch } = useForm();
  console.log(watch());
  return (
    <div>
      <form>
        <input {...register("name")} placeholder="name" />
        <button>Add</button>
      </form>
    </div>
  );
}

export default Home;

resgister 함수가 가지고 있는 객체

✔ register 함수가 반환하는 객체를 input의 props로 사용 할 수 있다.

watch 함수로 값 트래킹 하기

✅ handleSubmit

✔︎ handleSubmit : 사용자가 form을 제출했을 때, 즉 유효성 검사를 통과 후 submit할 때 실행되는 함수이다.

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

function Home() {
  const { register, handleSubmit } = useForm();

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

  return (
    <div>
      <form onSubmit={handleSubmit(onValid)}>
        <input {...register("name")} placeholder="name" />
        <input {...register("email")} placeholder="email" />
        <input {...register("password")} placeholder="password" />
        <input {...register("password2")} placeholder="password2" />
        <button>Add</button>
      </form>
    </div>
  );
}

export default Home;

✅ 조건 설정하기

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

function Home() {
  const { register, handleSubmit } = useForm();

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

  return (
    <div>
      <form onSubmit={handleSubmit(onValid)}>
        <input {...register("name", { required: true })} placeholder="name" />
        <input {...register("email", { required: true })} placeholder="email" />
        <input
          {...register("password", { required: true, minLength: 8 })}
          placeholder="password"
        />
        <input
          {...register("password2", { required: true, minLength: 8 })}
          placeholder="password2"
        />
        <button>Add</button>
      </form>
    </div>
  );
}

export default Home;

✅ formState

✔︎ formState : 이 개체에는 전체 양식 상태에 대한 정보가 포함되어 있다. 양식 응용 프로그램과 사용자의 상호 작용을 추적하는 데 도움이 된다.

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

function Home() {
  const { register, handleSubmit, formState } = useForm();

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

  console.log(formState.errors);

  return (
    <div>
      <form onSubmit={handleSubmit(onValid)}>
        <input {...register("name", { required: true })} placeholder="name" />
        <input {...register("email", { required: true })} placeholder="email" />
        <input
          {...register("password", { required: true, minLength: 8 })}
          placeholder="password"
        />
        <input
          {...register("password2", { required: true, minLength: 8 })}
          placeholder="password2"
        />
        <button>Add</button>
      </form>
    </div>
  );
}

export default Home;

form 제출 시 조건에 만족하지 못하면 에러를 발생 시킨다. 그리고 에러가 어떤 에러인지를 알려준다. 또한 아래와 같이 코드를 수정하면 에러발생 시 메세지를 보낼 수 있다.

 <input {...register("email", { required: "Email is Required" })} placeholder="email" />

✅ setValue

✔︎ setValue : 동적으로 input값을 설정할 수 있고, 양식 상태를 확인하고 업데이트하는 옵션을 가질 수 있다. 동시에 불필요한 렌더링을 피하려고 한다.

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

function Home() {
  const { register, handleSubmit, setValue } = useForm();
  const handleValid = (data) => {
    setValue("name", "");
  };
  return (
    <div>
      <form onSubmit={handleSubmit(handleValid)}>
        <input
          {...register("name", {
            required: "Please write your name",
          })}
          placeholder="Write your name"
        />
        <button>Add</button>
      </form>
    </div>
  );
}

export default Home;

3. 마무리

복잡한 Form을 만들 때 사용하면 간결하고 쉬운코드 작성에 도움이 될 것 같다.
react-hook-form을 이용하면, 단순히 몇 줄만으로도, 간단하고 강력한 validation을 검사 할 수 있기 때문이다.

profile
✍️ 👨🏻‍💻🔥➜👍🤔 😱

0개의 댓글