«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
Recent Posts
Recent Comments
관리 메뉴

뉴히의 개발 로그

[React hook form] 라이브러리 사용법 본문

개발일지/TIL

[React hook form] 라이브러리 사용법

뉴히 2024. 3. 19. 02:17

useForm

resister

register 함수의 두번째 인자값으로 옵션을 넘겨줄 수 있다.

  • required : 필수입력
  • min
  • max
  • minLength :최소길이
  • maxLength :최대길이
  • pattern { value: 정규식, message: 형식이 맞지않을때 전할 메세지 }
  • validate

aria-invalid

aria-invalid={errors.email ? 'true' : 'false'}

웹접근성을 위한 aria-invalid 속성을 추가하면 

사용자에게 시각적으로 안내 가능

그러나, 

aria-invalid사용시에는 isSubmitted 속성을 같이 사용해줘야 한다.

아무 정보가 없어도 박스에 초록불이 들어와 있기때문

 

isSubmitted  는 submit 버튼을 한번이라도 클릭하면 true, 클릭한적 없으면 false

 const {
        register,
        handleSubmit,
        formState: { isSubmitting, isSubmitted } // 추가
} = useForm();

.
.
.


aria-invalid={isSubmitted ? (errors.email ? 'true' : 'false') : undefined } // isSubmitted이 true일때만 aria-invalid

 

 

 

useForm 객체중 양식이 현재 어떤상태인지 담고있는 formState

formState 속성중 isSubmitting => 양식 제출중에는 버튼 비활성화 (더블 클릭등 이벤트 중복을 방지)

 const {
        register,
        handleSubmit,
        formState: { isSubmitting }
} = useForm();

return (
	 <form
        onSubmit={handleSubmit(async (data) => {
            await new Promise((r) => setTimeout(r, 1000));
            alert(JSON.stringify(data));
        })}>
        <div className="space-y-1.5">
            <div className="grid w-full items-center gap-4">
                <div className="flex flex-col space-y-1.5">
                    <Label htmlFor="email">이메일</Label>
                    <Input id="email" type="email" placeholder="example@example.com" {...register('email')} />
                </div>
            </div>
            <div className="grid w-full items-center gap-4">
                <div className="flex flex-col space-y-1.5">
                    <Label htmlFor="email">비밀번호</Label>
                    <Input id="password" type="password" placeholder="******" {...register('password')} />
                </div>
            </div>
        </div>
        <br />
        <div className="flex justify-between">
            <Button variant="ghost">회원가입</Button>
            <Button type="submit" disabled={isSubmitting}>
                로그인
            </Button>
        </div>
    </form>
)

 

formState: { isSubmitting }을 선언해주고

submit 버튼에 disable속성에 isSubmitting 을 넣어준다

 

 

그럼 로그인중일때는 로그인 버튼이 disable됨