React-hook-form

Hyun Kyung Nam·2024년 3월 29일
0

개념정리

목록 보기
9/14
post-thumbnail

Hook Form

  • React 어플리케이션에서 폼을 쉽게 관리
  • 폼의 상태 관리와 유효성 검사를 간단하게 만들어 줌
  • npm install react-hook-form으로 설치

register

  • 입력 요소에 연결하기 위한 함수. 이 함수를 통해 입력 요소에 유효성 검사 규칙을 설정
  • props로는 onChange, onBlur, name을 갖음
  • name은 필수이며 unique해야함.
    • 점과 대괄호도 지원하므로 중첩된 form field을 쉽게 만들 수 있음
    • 숫자 및 특수문자는 지양
    • typescript 사용 일관성을 위해 대괄호는 동작하지 않음
		register('test.0.firstName'); // ✅
		register('test[0]firstName'); // ❌
  • disabled input은 undefined 값을 리턴하므로 유저의 update를 막고 싶다면 readOnly 또는 전체 fieldset을 disable시키기 (예 : 예제)
  • 각각의 register option은 undefined또는 빈객체로 제거될 수 없음

props

NameTypeDescription
namestring등록될 input name
onChangeChangeHandlerinput change 이벤트 발생을 subscribe하는 prop
onBlurChangeHandlerinput에 blur 이벤트 발생을 subscribe하는 prop

Input name 등록 예시

inputNameSubmit Result
register("hi"){hi : input값}
register("Hi.hello"){Hi : {Hello : input값}}
register("Hi.hello.0"){Hi : {Hello : [input값]}}

ref prop을 이용한 register option

NameDescriptionCode Example
refReact element ref

<input {...register("test")} />

requiredtrue이면 submit전에 input값을 가져야하며 errors객체를 이용하여 error message를 할당 가능

<input {...register("test", { required: 'error message'}})}/>

maxLengthinput 값 최대길이

<input{...register("test", { maxLength : { value: 2, message: 'error message' }})}/>

minLengthinput값 최소 길이

<input{...register("test", { minLength : { value: 1, message: 'error message' }})}/>

maxinput에 들어올 수 있는 최대값

<input type="number" {...register('test', { max: { value: 3, message: 'error message' } })} />

이 외 여러가지는 공식문서를 참고 하면 좋을 듯 하다
링크 : hook-form/register

에러메세지는 JS에서는 p태그, TS는 string을 지원

이메일 정규화식

handleSubmit

  • 폼의 제출을 처리하기 위한 함수. 이 함수에 전달된 콜백은 유효성 검사를 통과한 데이터를 인자로 받아 실행
  • handleSubmit으로 비동기 폼 제출 가능(동기처리도 가능)
  • 비동기 handleSubmit 사용시 try catch를 사용해 error처리 하는것 추천
	const onSubmit = async () => {
		try {
		} catch(e) {
    	}
	};

props

NameTypeDescription
SubmitHandler(data : Object, e?:Event) => Promisesuccess callback
SubmitErrorHandler(errors:Object, e?:Event) => Promiseerror callback

사용법

    const onSubmit = (data: object) => {
        console.log(data);
    };
      const onInvalid = (errors: object) => {
  // required가 만족하지 않거나 하면 errorHandler로 들어옴
        console.log(errors);
    };
  <form onSubmit={handleSubmit(onSubmit, onInvalid)}>
  
  </form>

watch

  • (names?: string | string[] | (data, options) => void) => unknown
  • 특정 폼 필드의 값을 실시간으로 관찰하는 함수
  • 기본 값이 정해져있지 않으면 register 되기 전에 첫 렌더링이 발생하므로 undefined가 return됨 이를

props

TypeDescription
stringwatch input value by name
string[]watch multiple inputs
undefinedwatch all inputs
(data:unknown, {name : string, type :string}) => voidwatch all inputs and invoke a callback

사용 예시

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

interface IFormInputs {
  name: string
  showAge: boolean
  age: number
}

function App() {
  const {
    register,
    watch,
    formState: { errors },
    handleSubmit,
  } = useForm<IFormInputs>()
  const watchShowAge = watch("showAge", false) // you can supply default value as second argument
  const watchAllFields = watch() // when pass nothing as argument, you are watching everything
  const watchFields = watch(["showAge", "age"]) // you can also target specific fields by their names

  // Callback version of watch.  It's your responsibility to unsubscribe when done.
  React.useEffect(() => {
    const subscription = watch((value, { name, type }) =>
      console.log(value, name, type)
    )
    return () => subscription.unsubscribe()
  }, [watch])

  const onSubmit = (data: IFormInputs) => console.log(data)

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <input {...register("name", { required: true, maxLength: 50 })} />
        <input type="checkbox" {...register("showAge")} />
        {/* based on yes selection to display Age Input*/}
        {watchShowAge && (
          <input type="number" {...register("age", { min: 50 })} />
        )}
        <input type="submit" />
      </form>
    </>
  )
}

formState

  • 폼의 상태를 나타내는 객체(errors, isValid, isDirty, isSubmitted 등의 상태를 포함)
  • 그 중 error를 사용하면 쉽게 설정해둔 error를 표시할 수 있다
    const {
        register, //input 할당, value 변경 감지
        handleSubmit, // form submit될 때 호출
        formState: { errors }, // 폼상태 객체, errors값이 들어있음
        watch, // 특정한 폼 필드의 값을 실시간으로 사용
    } = useForm();
  
  
	<input
		type="text"
		 placeholder="username"
		//name="username"으로 썼었는데 이걸 register에 명시해주는것
		//뒤에는 객체형태로 옵션넣어주면된다
		//오류 메세지도 지정가능
		{...register('username', {
			required: '이름을 입력해주세요.',
			minLength: {
 			message: '이름은 최소 2글자 이상 작성해주세요.',
			value: 2,
		 	},
		})}
 	/>
  	{errors.username?.message}
  	//?는 있으면 실행 없으면 실행하지 않는 다는 의미를 뜻함.

hook-form에 대해서 스치듯 지나갔는데 이렇게 다시 복습하니까 조오금 알 것도 같다. 이제 이걸 가지고 작은 component를 만들어 사용하는 것을 작성할 예정이다. react는 대충 깔짝거려서 만들수도, 정말 공부를 많이 하고서 이런 저런 다양한 활용을 할수도 있는 것 같다. 그동안 방황한거 만회하려면 열심히 공부해서 열심히 블로깅해야지. 리액트는 정말 많이 공부해야하는게 느껴지니까..! 찾아보고 정리하고 적용하고 발전시키고 재밌다!

참고 : 코딩온 교안 , react-hook-form 공식 문서

0개의 댓글