[TIL] React-hook-form을 쓰면 좋은점

👉🏼 KIM·2024년 11월 2일

TIL

목록 보기
29/54

오늘 공부한것 & 기억하고 싶은 내용

React-hook-form을 쓰면 좋은점

validation 유효성 검사가 간단해진다.

  • register의 옵션 객체에 들어가며, 값은 하나의 함수가 될 수도 있고, 함수들이 들어있는 객체가 될 수도있음
  • required를 객체 안에 넣어줌으로써 html 개발자 도구에서 변경할 수 있는 걸 숨겨줌
  • 필수값에 값을 넣지 않으면 알아서 비어있는 입력창으로 커서를 옮겨준다.
    - 원래 이걸 하려면 데이터 없는 걸 찾아서 그곳에 포커스를 맞춰줘야하는 번거로움을 방지
  • 값의 길이도 attribute 한줄 추가로 가능하다. (minLength)
  • formState: error의 종류도 알려주고, 메시지도 따로 작성 가능하다. 모든 속성에 message 작성 가능
  • pattern도 만들 수 있음 : 이메일 형식을 정규식표현으로 지정해줄 수도 있다.
  • 에러 메시지를 화면에 뿌려줄수도 있음
  • 비밀번호가 일치하지 않은지 확인하는 방법
  • setError은 특정한 에러를 발생시키게 해준다.
  • shouldFocus는 에러가 난 곳으로 강제로 포커스 가능
  • validate 값은 T/F값을 받음. 객체형식으로 여러 개를 관리 가능 / 현재 받은 값에 대하여 유효성검사를 해줌
interface IForm {
  email: string;
  firstName: string;
  lastName: string;
  username: string;
  password: string;
  password1: string;
  extraError?: string;
}

function ToDoList() {
  const {
    register,
    handleSubmit,
    formState: { errors },
    setError,
  } = useForm<IForm>({
    defaultValues: {
      email: "@naver.com",
    },
  });
  const onValid = (data: IForm) => {
    if (data.password !== data.password1) {
      setError(
        "password1",
        { message: "Password are not the same" },
        { shouldFocus: true }
      );
    }
    // setError("extraError", { message: "Server offline." });
  };
  console.log(errors);
  return (
    <div>
      <form
        style={{ display: "flex", flexDirection: "column" }}
        onSubmit={handleSubmit(onValid)}
      >
        <input
          {...register("email", {
            required: "Email is required",
            pattern: {
              value: /^[A-Za-z0-9._%+-]+@naver.com$/,
              message: "Only naver.com emails allowed",
            },
          })}
          placeholder="Email"
        />
        <span>{errors?.email?.message}</span>
        <input
          {...register("firstName", {
            required: "write here",
            validate: {
              noMinho: (value) =>
                value.includes("minho") ? "no minho allowed" : true,
              noNick: (value) =>
                value.includes("nick") ? "no nick allowed" : true,
            },
          })}
          placeholder="First Name"
        />
        <span>{errors?.firstName?.message}</span>
        <input
          {...register("lastName", { required: "write here" })}
          placeholder="Last Name"
        />
        <span>{errors?.lastName?.message}</span>
        <input
          {...register("username", { required: "write here", minLength: 10 })}
          placeholder="Username"
        />
        <span>{errors?.username?.message}</span>
        <input
          {...register("password", { required: "write here", minLength: 5 })}
          placeholder="Password"
        />
        <span>{errors?.password?.message}</span>
        <input
          {...register("password1", {
            required: "Password is required",
            minLength: {
              value: 5,
              message: "Your password is too short.",
            },
          })}
          placeholder="Password1"
        />
        <span>{errors?.password1?.message}</span>
        <button>Add</button>
        <span>{errors?.extraError?.message}</span>
      </form>
    </div>
  );
}

배운점 & 느낀점

강의 #6.7-6.8을 듣고 정리해보았다.
생각보다 폼 쪽 작업할게 많은데 이 훅은 정말 말도 안되는 거 같다..
리액트로 회원가입 만들기 세상에서 제일 간단할듯!!

profile
프론트는 순항중 ¿¿

0개의 댓글