[react]react-hook-form : useForm, react hook for form validation

박주연·2023년 1월 14일
0

React

목록 보기
1/6

main project에서 로그인 회원가입 쪽 기능 구현을 맡게 되어 react-hook-form을 사용하게 되었다.

react-hook-form의 장점

  1. 간결한 코드
    • 각각의 항목(이름, 이메일, 비밀번호 등)에 대한 상태를 바꾸고 저장하는 useState 구문을 반복해서 작성할 필요가 없다.
    • {...register('...')} 하나면 값이 저장된다.
  2. 기본 제공되는 다양한 기능들
    • 기본 제공되는 메소드나 객체를 이용하여 쉽게 유효성 검사를 할 수 있다.

새로 알게된 점

  • 로그인 / 회원 가입 기능 구현을 위해 form 코드를 구현하면서 새로 알게된 사실
  1. 로그인/회원가입을 감싸는 전체 틀은 form 태그를 사용해야 한다.
  2. form tag에 onSubmit 속성을 넣어줄 수 있다.

react-hook-form / useForm 사용

  • react-hook-form 설치
    npm i react-hook-form
  • useForm 가져오기
    import { useform } from 'react-hook-form';
  • useForm에서 사용할 수 있는 메소드 / 객체 불러오기
    const { handleSubmit, register, ...등 } = useForm(여기에는 mode가 추가될 수 있다.)

react-hook-form 의 기능

  1. mode
    const { register, handleSubmit } = useForm({mode: "onChange"})
    onChange mode는 input 값의 변화에 따라 에러 메시지의 유무를 변화시켜 주고 싶을 때 유용하다.

  2. formState / isValid / isDirty
    const {register, handleSubmit, formState: {errors, isValid, isDirty}} = useForm()

    • formState : This object contains information about the entire form state. It helps you to keep on track with the user's interaction with your form application.
    • isValid : form의 값이 유효한가?
    • isDirty : form의 값이 modified 되었는가?
    • errors : input에 error가 있는가?
  3. register

    const Login = () => {
    const loginButtonClick = async (data) => {
        const { password } = data;
        console.log(data);
    }
        return (
            <>
                <form onSubmit={handleSubmit(data => loginButtonClick(data))}>
                    <label htmlFor="password"></label>
                      <input
                          type: "password",
                          id: "password",
                          {...register("password", {
                              required: true,
                              pattern: passwordRegex // (정규표현식)
                          })}
                      />
                      <button type="submit">로그인</button>
                </form>
            </>
        )
    
    }
    // 버튼 클릭하면 input에 입력한 값이 data에 담기고,
    // {password: 'input에 입력한 값'} 이 찍한다.
    // 나중에 이 값을 이용하여 서버에 POST 요청을 보내 로그인을 시도할 수 있다.
    

문제 해결

회원 가입 폼을 작성하면서, 두가지 기능을 추가하고 싶었다.
1. input값의 변화에 따라 에러메시지를 보여주는 것이었고,
2. form의 모든 항목이 유효성 검사를 통과하면 버튼이 active해지는 것이었다.
구글에 'react-hook-form button disabled' 라고 검색하여 찾은 자료의 도움을 받아 두가지 기능을 구현할 수 있었다.
1. mode: "onChange"
2. formState와 isValid
https://stackoverflow.com/questions/65255298/how-to-conditionally-disable-the-submit-button-with-react-hook-form

profile
Zoë Park

0개의 댓글