뉴히의 개발 로그
[React hook form] 라이브러리 사용법 본문
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됨
'개발일지 > TIL' 카테고리의 다른 글
z-index 적용 안됨 현상, z-index란? stacking context란? (0) | 2024.05.02 |
---|---|
typescript '() => void' 형식은 'MouseEventHandler<HTMLDivElement>' 형식에 할당할 수 없습니다 (0) | 2024.03.26 |
클라이언트 사이드 렌더링(CSR)과 서버 사이드 렌더링(SSR)의 개념, 장/단점 (0) | 2023.11.13 |
RESTFul API란 (0) | 2023.10.30 |
프레임워크(Framework)와 라이브러리(Library)의 차이 (0) | 2023.10.20 |