react hook으로 form을 쉽게 만들 수 있도록 도와줌
설치
npm i react-hook-form
기본 예제
import React from "react";
import { useForm } from "react-hook-form";
Interface Inputs = {
example: string,
exampleRequired: string,
};
export default function App() {
const { register, handleSubmit, watch, errors } = useForm<Inputs>({mode: "onChange"});
const onSubmit = data => console.log(data);
const onSubmitInvalid = data => console.log(data);
console.log(watch("example"))
return (
<form onSubmit={handleSubmit(onSubmit, onSubmitInvalid)}>
<input name="example" defaultValue="test" ref={register} />
<input name="exampleRequired" ref={register({ required: true })} />
{errors.exampleRequired && <span>This field is required</span>}
<input type="submit" />
</form>
);
}