react-hook-form에대해서 간단히 정리하였는데 vaildation부분에서 yup을 추가 하여 register안에 작성하던 것을 바깥 부분으로 뺄 수 있습니다.
"use client";
import { FormEvent, useEffect } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
type auth = {
email: string;
password: string;
};
export default function Home() {
const { register, handleSubmit, watch, formState, setValue } = useForm<auth>({
mode: "onChange",
});
useEffect(() => {
setValue("email", "qube7089");
setValue("password", "test");
}, [setValue]);
const eventHandler: SubmitHandler<auth> = (data) => {
console.log(data.email);
console.log(data.password);
};
return (
<form onSubmit={handleSubmit(eventHandler)}>
<div className="m-auto w-[200px] h-[200px] border border-solid border-black">
<input
{...register("email", {
required: "필수 입력사항입니다.",
pattern: {
value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
message: "이메일 형식으로 입력해주시기 바랍니다.",
},
value: "test",
})}
placeholder="email"
/>
{formState.errors.email?.message && (
<p>{formState.errors.email?.message}</p>
)}
<input
{...register("password", { required: "필수 입력사항입니다." })}
/>
<button
type="submit"
className={formState.isValid ? "bg-blue-500" : "bg-gray-300"}
>
로그인
</button>
</div>
</form>
);
}
위에 어제 작성했던 코드에서 우선은 yup을 다운로드 합니다.
npm install @hookform/resolvers yup
yarn add @hookform/resolvers yup
2개의 라이브러리를 다운로드하고 schema를 작성할 것 입니다.
import * as yup from "yup";
const schema = yup.object({
email: yup
.string()
.required("필수 입력 사항입니다.")
.matches(
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
"이메일 형식으로 입력해주시기 바랍니다."
),
password: yup.string().required("필수 입력 사항입니다."),
});
위와 같이 작성할 수 있습니다.
작성한 schema를 usrForm에 작성합니다.
import { yupResolver } from "@hookform/resolvers/yup";
const { register, handleSubmit, watch, formState, setValue } = useForm<auth>({
mode: "onChange",
// 이 부분에서 작성한 schema가 들어감 들어감
resolver: yupResolver(schema),
});
위와같이 resolver에 들어가게 되고 @hookform/resolvers/yup에서 yupResolver를 가져와 인자로 작성한 schema가 들어가게 됩니다.
그러면 기존에 작성했던 validation부분을 지우고 위에 코드들을 적용하면 아래와 같이 적용합니다.
"use client";
import { yupResolver } from "@hookform/resolvers/yup";
import { FormEvent, useEffect } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import * as yup from "yup";
// schema작성
const schema = yup.object({
email: yup
.string()
.required("필수 입력 사항입니다.")
.matches(
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
"이메일 형식으로 입력해주시기 바랍니다."
),
password: yup.string().required("필수 입력 사항입니다."),
});
type auth = {
email: string;
password: string;
};
export default function Home() {
const { register, handleSubmit, watch, formState, setValue } = useForm<auth>({
mode: "onChange",
// 이 부분에서 작성한 schema가 들어감 들어감
resolver: yupResolver(schema),
});
useEffect(() => {
setValue("email", "qube7089");
setValue("password", "test");
}, [setValue]);
const eventHandler: SubmitHandler<auth> = (data) => {
console.log(data.email);
console.log(data.password);
};
return (
<form onSubmit={handleSubmit(eventHandler)}>
<div className="m-auto w-[200px] h-[200px] border border-solid border-black">
<input {...register("email")} placeholder="email" />
{formState.errors.email?.message && (
<p>{formState.errors.email?.message}</p>
)}
<input {...register("password")} />
<button
type="submit"
className={formState.isValid ? "bg-blue-500" : "bg-gray-300"}
>
로그인
</button>
</div>
</form>
);
}
커스텀 훅 등을 사용하면 컴포넌트에서는 vaildation및 각종 비지니스 로직을 관리할 수 있습니다.