📍참고
https://www.react-hook-form.com/get-started
📍예시 코드 1
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit, watch, formState: { errors } } = useForm();
const onSubmit = data => console.log(data);
console.log(watch("example")); // input 밸류 이름을 watch 함수에 전달하여 값 확인
return (
/* handleSubmit은 onSubmit을 호출하기 전에 입력 유효성 검증 실행 */
<form onSubmit={handleSubmit(onSubmit)}>
{/* register함수를 호출하여 입력을 hook에 등록 */}
<input defaultValue="test" {...register("example")} />
{/* required 같은 HTML 어트리뷰트 유효성 검증을 포함 */}
<input {...register("exampleRequired", { required: true })} />
{/* 필드 유효성 검증이 실패하면 에러 발생 */}
{errors.exampleRequired && <span>This field is required</span>}
<input type="submit" />
</form>
);
}
register("input 이름") : 컴포넌트 내부에서 사용될 "input 이름"을 등록
📍예시 코드 2
register로 등록한 필드만 form 제출 및 유효성 검증에 사용할 수 있다
import { useForm, SubmitHandler } from "react-hook-form";
interface FormInput {
firstName: string;
gender: "female" | "male" | "other";
}
export default function FormTwo() {
const { register, handleSubmit } = useForm<FormInput>();
const onSubmit: SubmitHandler<FormInput> = (data) => console.log(data);
/* data = {
firstName: string,
gender: "female" | "male" | "other"
}
*/
return (
<form className="flex flex-col gap-5" onSubmit={handleSubmit(onSubmit)}>
<label>First Name</label>
<input {...register("firstName")} />
<label>Gender Selection</label>
{/* <select> 아래의 키-밸류 형태를 만들 수도 있다 */}
<select {...register("gender")}>
<option value="female">female</option>
<option value="male">male</option>
<option value="other">other</option>
</select>
<input type="submit" />
</form>
);
}
📍예시 코드 3
기존 HTML input 엘리먼트의 validation attributes를 활용할 수 있음
- required
- min
- max
- minLength
- maxLength
- pattern
- validate
import { useForm, SubmitHandler } from "react-hook-form";
interface FormInput {
firstName: string;
lastName: string;
age: number;
}
export default function FormThree() {
const { register, handleSubmit } = useForm<FormInput>();
const onSubmit: SubmitHandler<FormInput> = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName", { required: true, maxLength: 20 })} />
{/* 정규식을 등록하는 것도 가능 */}
<input {...register("lastName", { pattern: /^[A-Za-z]+$/i })} />
<input type="number" {...register("age", { min: 18, max: 99 })} />
<button>Submit</button>
</form>
);
}
📍예시 코드 4
register 함수를 props로 전달할 수도 있다
import { forwardRef } from "react";
import { Path, useForm, UseFormRegister, SubmitHandler } from "react-hook-form";
interface FormValues {
"First Name": string;
Age: number;
}
interface InputProps {
label: Path<FormValues>;
register: UseFormRegister<FormValues>;
required: boolean;
}
export default function FormFour() {
const { register, handleSubmit } = useForm<FormValues>();
const onSubmit: SubmitHandler<FormValues> = (data) =>
alert(JSON.stringify(data));
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Input label="First Name" register={register} required />
<Select label="Age" {...register("Age")} />
<input type="submit" />
</form>
);
}
// register를 props로 전달받음
function Input({ label, register, required }: InputProps) {
return (
<>
<label>{label}</label>
<input {...register(label, { required })} />
</>
);
}
const Select = forwardRef<
HTMLSelectElement,
{ label: string } & ReturnType<UseFormRegister<FormValues>>
>(({ onChange, onBlur, name, label }, ref) => (
<>
<label>{label}</label>
<select name={name} ref={ref} onChange={onChange} onBlur={onBlur}>
<option value="20">20</option>
<option value="30">30</option>
</select>
</>
));
📍예시 코드 5
외부 UI 컴포넌트를 활용할 수 있다. Controller 컴포넌트 내부에 control, render 어트리뷰트와 함께 작성하면 된다
import Select from "react-select";
import { useForm, Controller, SubmitHandler } from "react-hook-form";
import Input from "@material-ui/core/Input";
interface FormInput {
firstName: string;
lastName: string;
iceCreamType: { label: string; value: string };
}
const App = () => {
const { control, handleSubmit } = useForm({
defaultValues: {
firstName: '',
lastName: '',
iceCreamType: {}
}
});
const onSubmit: SubmitHandler<FormInput> = data => {
console.log(data)
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="firstName"
control={control}
render={({ field }) => <Input {...field} />}
/>
<Controller
name="iceCreamType"
control={control}
render={({ field }) => <Select
{...field}
options={[
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
]}
/>}
/>
<input type="submit" />
</form>
);
};
📍예시 코드 6
errors 객체를 통해 유효성 검증에 따른 에러를 표시할 수 있다
import { useForm, SubmitHandler } from "react-hook-form";
interface FormInputs {
firstName: string;
lastName: string;
}
export default function FormFive() {
const {
register,
formState: { errors },
handleSubmit,
} = useForm<FormInputs>();
const onSubmit: SubmitHandler<FormInputs> = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName", { required: true })} />
{errors.firstName && "FirstName is required"}
<input {...register("lastName", { required: true })} />
{errors.lastName && "LastName is required"}
<input type="submit" />
</form>
);
}