[React] react-hook-Form (form 라이브러리, input)

mangosteen·2024년 3월 18일

react

목록 보기
5/8

기존의 Form 사용 방식

useState를 사용해서 각 input의 입력의 validation, error 등 확인 및 값 저장이 필요.

import { useState } from "react";

function ToDoList() {
  const [toDo, setToDo] = useState("");
  const [toDoError, setToDoError] = useState("");
  const onChange = (event: React.FormEvent<HTMLInputElement>) => {
    const {
      currentTarget: { value },
    } = event;
    setToDo(value);
    setToDoError("");
  };
  const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (toDo.length < 10) {
      return setToDoError("To do should be longer");
    }
    console.log("submit");
  };
  return (
    <div>
      <form onSubmit={onSubmit}>
        <input
          value={toDo}
          onChange={onChange}
          type="text"
          placeholder="Write a to do"
        />
        <button>Add</button>
        {toDoError !== "" ? toDoError : null}
      </form>
    </div>
  );
}
export default ToDoList;

react-hook-form 사용하기

form 라이브러리 사용하는 방법

react-hook-form
https://react-hook-form.com/get-started
https://legacy.react-hook-form.com/v6/api/

  1. npm install react-hook-form 설치
  2. useForm import하여 사용.
  • register() : onChange, onBlur등의 이벤트 등이 포함 된 객체를 반환.
// console.log(register("toDo"))
name: "toDo"
onBlur:async event => {…}
onChange: async event => {…}
ref: ref => {…}

input에 {...register("name")}형태로 register가 반환하는 객체들을 펼쳐서 input의 props로 부여.

 <input {...register("Email")} placeholder="Email" />
  • RegisterOptions : input 입력에 대한 option 및 메세지 추가.
    RegisterOptions이 입력되지 않았을 경우, 입력되지 않은 값의 input에 focus동작하고, form입력값이 onValid로 넘어가지 않음.
    RegisterOptions 조건에 대한 내용은 Ctrl + required 클릭해서 확인(validator.d.ts).

        <input
          {...register("password", { required: true, minLength: 5 })}
          placeholder="password"
        />
// 메세지 추가
       <input
          {...register("FirstName", {
            required: "First name is required",
            minLength: {
              value: 2,
              message: "your first name is way too short",
            },
          })}
          required
          placeholder="FirstName"
        />

정규식(regular expressions)를 이용해서 validation 확인도 가능

regex 참고
https://regex101.com/
https://www.regexpal.com

        <input
          {...register("Email", {
            required: true,
            pattern: {
                value :  /^[A-Za-z0-9._%+-]+@naver.com$/,
                message : "Only naver.com emails allowed"
            }
          })}
          placeholder="Email"
        />

validate로 input내에서 별도의 값 확인도 가능.
바로 string을 return하면(validate:"string") errors.message로 동작.
validate 여러 개의 조건일 경우. 오브젝트 형태로 쓸 수 있다.

<input
          {...register("firstName", {
            required: "First name is required",
            minLength: {
              value: 2,
              message: "your first name is way too short",
            },
            validate: (value) =>
              value.includes("subin") ? "no subin is allowed" : true,
// firstName 값에 subin이 포함되지 않을 경우만 validation true 확인.
          })}
          placeholder="firstName"
        />
// validate 여러 개

        <input
          {...register("userName", {
            required: "Write here",
            validate: 
              noSubin: (value) =>
                value.includes("subin") ? "no subin is allowed" : true,
              noNico: (value) =>
                value.includes("nico") ? "no nico is allowed" : true,
            },
          })}
          placeholder="userName"
        />
  • formState : RegisterOptions에 부합하지 않은 input에 대해 formState.errors(formState : { errors })로 확인 가능
password1:{type: 'minLength', message: '', ref: input}
  • watch() : form의 입력값 변화를 관찰.
  • handleSubmit() : onSubmit 대체, validation, preventDefault 기능.
    handleSubmit은 onValid()함수 필요.
    RegisterOptions이 모두 부합한 경우, onValid 함수에서 다시 입력값, 혹은 각종 에러를 체크할 수 있음.
      <form onSubmit={handleSubmit(onValid)}>
  • setError: 에러 발생시킴.
    shouldFocus: true 일 경우, 해당 에러 위치로 focus이동시킴.
const onValid = (data: IForm) => {
      setError(
        "password1",
        { message: "Password are not the same" },
        { shouldFocus: true }
      );
    }
  };
  • setValue : input 값 수정
  const handleValid = (data: IForm) => {
    setValue("password1", "");
  };
profile
Mong muốn trở thành chủ cuộc sống của tôi🔥.

0개의 댓글