React Hook Form

yezee·2023년 4월 24일
0

라이브러리

목록 보기
7/8
post-thumbnail

form이 많은 프로젝트를 할 때 수많은 state와 유효성검사를 쉽게 하기 위해 만들어진 라이브러리입니다

설치

npm install react-hook-form

사용하기

  1. useForm을 import한다
  2. 컴포넌트에서 useForm을 호출하면 register와 handleSubmit이 제공된다
  3. register함수를 form에 있는 모든 input에서 호출한다(검사옵션을 설정할 수 있다)
  • useForm()
    const {register,watch,handleSubmitformState:{errors},setError,}=useForm({defalutValues:{email:"@naver.com"}})
  • register
    register함수를 사용하면 onChange,onSubmit과 같은 이벤트 핸들러가 필요없어진다
    그말인즉슨 useState()로 관리할 필요도 없어진다는 뜻이다
    <input
          {...register('password', {
            required: 'password is required',
            minLength: { value: 5, message: 'Your password is too short' },
          })}
          placeholder='password'
        />
  • watch
    watch는 form의 입력값들의 변화를 관찰할 수 있게 해주는 함수
    이 함수를 통해 form의 입력값을 추적할 수 있다

  • handleSubmit
    유효성검사를 위한 함수
    <form onSubmit={handleSubmit(onValid)}></form>
    onValid함수가 호출되었다면, form이 모든 validation을 통과했다는 말

required: true -> boolean을 이용한 필수값
required: "대답을 작성하지 않았습니다" -> error 발생시 유저에게 보여줄 에러를 작성
minLength: { value: 5, message: 'Your password is too short' }
pattern:{/^[A-ZA-z0-9._%+-]+@naver.com$/, message:""} ->정규식을 이용해서 들어가야할 값을 지정할 수 있다 ex)이메일

mport { useForm } from 'react-hook-form';

interface IForm {
  email: string;
  name: string;
  password: string;
  password1: string;
}

function TodoList() {
  const {
    register,
    handleSubmit,
    formState: { errors }, 
    setError,
  } = useForm<IForm>({
    defaultValues: {
      email: '@naver.com', 
    },
  }); //useForm() 훅을 통해 모든 유효성검사,state들을 대체할 수 있다
  
const onValid = (data: IForm) => { 
  //onValid함수는 form의 데이터가 유효할때만 호출되는 함수
  
  //패스워드 일치검사하는 방법
    if (data.password !== data.password1) {
      setError('password', 
               { message: 'password are not the same' },//패스워드 불일치 시, error메시지
               {shouldFoucus:true}); //불일치 된 곳으로 focus이동
    }
  };
  return (
    <div>
      <form onSubmit={handleSubmit(onValid)}>
        <input
          {...register('email', {
            required: 'email',
            pattern: {
              value: /^[A-Za-z0-9._%+-]+@naver.com$/,
              message: 'Only naver.com emails allowed',
            },
          })}
          placeholder='email'
        />
        <span>{errors?.email?.message as string}</span>
        <input
          {...register('name', { required: 'name is required' })}
          placeholder='Name'
        />
        <input
          {...register('password', {
            required: 'password is required',
            minLength: { value: 5, message: 'Your password is too short' },
          })}
          placeholder='password'
        />
        <span>{errors?.password?.message as string}</span>

        <input
          {...register('password1', {
            required: 'password is required',
            minLength: { value: 5, message: 'Your password is too short' },
          })}
          placeholder='password'
        />
        <span>{errors?.password1?.message as string}</span>

        <button>Add</button>
      </form>
    </div>
  );
}

export default TodoList;t;
profile
아 그거 뭐였지?

0개의 댓글