1. React Hook Form
- 폼 관리와 데이터 수집을 용이하게 해주는 라이브러리
- 복잡한 상태 관리 없이 폼 상태(필드값, 에러, 제출 상태 등)를 쉽게 추적하고 제어할 수 있다.
- 기본적으로 비제어 컴포넌트 방식으로 불필요한 리렌더링을 최소화하고, 필요한 경우에만 업데이트를 수행하여 애플리케이션 성능을 유지한다.
설치
npm install react-hook-form
2. Zod
- TypeScript-first 스키마 선언 및 유효성 검사 라이브러리
- TypeScript와 함께 사용할 수 있도록 설계되어 데이터 구조의 정적 타입스크립트 타입을 자동으로 추론할 수 있다.
- 타입과 유효성 규칙을 하나의 객체로 통합하여 유지보수성을 높이고 코드의 가독성을 향상시킨다.
npm install zod
or
npm install zod@canary // 실험적인 기능 포함
3. 스키마 유효성 검사
데이터 구조가 특정 스키마를 올바르게 지키고 있는지 확인하여 애플리케이션에 대한 정적 문서를 제공하고 사용자 입력의 유효성을 보장한다.
설치
해당 모듈은 React Hook Form에 Zod와 같은 외부 유효성 검사 라이브러리를 사용할 수 있게 해준다.
npm install @hookform/resolvers
스키마 작성 및 타입 추론
이메일 필드와 비밀번호 필드를 가진 로그인 폼의 스키마를 작성했고 Zod의 infer 메서드를 사용해 타입을 추론했다.
import { z } from 'zod';
export const LoginSchema = z.object({
email: z
.string({ required_error: '이메일을 입력해주세요' })
.min(1, { message: '이메일을 입력해주세요' })
.email({ message: '이메일 형식이 올바르지 않습니다' }),
password: z.string({ required_error: '비밀번호를 입력해주세요' }).min(1, { message: '비밀번호를 입력해주세요' }),
});
type TLoginForm = z.infer<typeof LoginSchema>;
useForm에 적용하기
import { zodResolver } from '@hookform/resolvers/zod';
const {
register,
formState: { errors },
} = useForm<TLoginForm>({
mode: 'onTouched',
resolver: zodResolver(LoginSchema),
defaultValues: { email: '', password: '' },
});
벨리데이션 메시지 출력
벨리데이션 메시지를 출력하는 컴포넌트를 만들어 재사용했다.
...
{errors.email && <ValidationMessage message={errors.email?.message} />}
...
import React from 'react';
import { ExclamationCircleIcon } from '@heroicons/react/24/outline';
interface IValidationMessageProps {
message?: string;
}
export default function ValidationMessage({ message }: IValidationMessageProps) {
return (
<div className="mt-2 flex items-center">
<ExclamationCircleIcon className="w-3.5 text-red-500" />
<p className="text-xs italic text-red-500"> {message || ''}</p>
</div>
);
}
'React' 카테고리의 다른 글
Storybook 알아보기 (1) | 2024.06.11 |
---|---|
Vite 기반 리액트 프로젝트와 Next.js 프로젝트에서 폰트 Preload 구현 (1) | 2024.06.05 |
핵심 웹 지표(Core Web Vitals) 정리 (0) | 2024.05.28 |
Redux와 Redux Toolkit으로 상태 관리하기 (0) | 2024.05.26 |
폰트 최적화 알아보기 (0) | 2024.05.25 |