날짜: 2024-07-09
React Hook Form의 useForm
훅 사용법에 대해 설명해 드리겠습니다.
useForm
은 React Hook Form 라이브러리의 핵심 기능으로, 폼 상태 관리와 유효성 검사를 쉽게 할 수 있게 해줍니다. 주요 사용법은 다음과 같습니다:
import { useForm } from "react-hook-form";
function MyForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName", { required: true })} />
{errors.firstName && <span>This field is required</span>}
<input {...register("lastName", { required: true })} />
{errors.lastName && <span>This field is required</span>}
<input type="submit" />
</form>
);
}
const { register, handleSubmit } = useForm({
defaultValues: {
firstName: "John",
lastName: "Doe"
}
});
<input {...register("age", { min: 18, max: 99 })} />
const { register, handleSubmit } = useForm({
validate: {
username: (value) => value.length > 5 || "Username must be longer than 5 characters"
}
});
const { watch } = useForm();
const watchUsername = watch("username");
const { formState: { errors } } = useForm();
// 사용:
{errors.username && <span>{errors.username.message}</span>}
const { reset } = useForm();
// 사용:
reset();
const { fields, append, remove } = useFieldArray({
control,
name: "items"
});
const { register } = useForm();
<input {...register("example")} />;
const { watch } = useForm();
const watchShowAge = watch("showAge", false);
return (
<form>
<input type="checkbox" {...register("showAge")} />
{watchShowAge && <input type="number" {...register("age")} />}
</form>
);
useForm
은 이외에도 다양한 기능을 제공합니다. 폼의 복잡성에 따라 적절한 기능을 선택하여 사용할 수 있습니다.