React/React Hook Form
2023/08/31__React(ReactHookForm)
HELLICAT
2023. 8. 31. 18:30
반응형
React-Hook-Form
React Hook Form라이브러리를 사용하면 따로 이벤트 헨들러, state를 만들 필요가 없다.
// 기존
export default function Mainpage() {
const [val, setVal] = useState("");
const onChange = (event: React.FormEvent<HTMLInputElement>) => {
const {
currentTarget: {value},
} = event;
setVal(value);
};
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
console.log("submit")
};
return (
<div>
<h1>React / Recoil / StyledComponent / TypeScript / To Do List</h1>
<form onSubmit={onSubmit}>
<input type="text" value={val} onChange={onChange} />
<button>Add</button>
</form>
</div>
);
}
1-1. register()
register 함수를 사용하면 onChange 이벤트 핸들러, props, state 가 필요가 없다.
register 함수에는
- name
- onChnage
- onBlur
- ref
가 내포되어 있다. react input의 attribute라고 생각되면 됨
1-2. watch()
watch는 form의 입력값들의 변화를 관찰 할 수 있게 해주는 함수
1-3. handleSubmit( onValid(required), onInValid(optional))
validation을 담당함 . handleSubmit에는 2개의 인자를 받는데 하나는 데이터가 유효할 때 호출되는 함수
다른 하나는 실패했을 때 호출 되는 함수
1-4.formState
console.log(formState.errors)를 하게 되면 해당부분에 떤 에러가 났는지 디버깅 할수 있다.
interface IFormData {
todo: string;
email: string;
errors: {
email: {
message: string;
};
};
}
export default function Mainpage() {
const {
register,
watch,
handleSubmit,
formState: {errors},
} = useForm<IFormData>();
const onValid = (data: any) => {
console.log(data);
};
return (
<div>
<h1>React / Recoil / StyledComponent / TypeScript / To Do List</h1>
<form onSubmit={handleSubmit(onValid)}>
{/* // register안에 required를 작성해 html의 소스코드를 보호할수 있다. */}
<input
{...register("todo", {
required: true,
minLength: {
value: 5,
message: "length is too short",
},
})}
type="text"
placeholder="Write a to do"
/>
<input
{...register("email", {
required: "emai is required",
minLength: 5,
pattern: {
value: /^[A-Za-z0-9._-]*@[A-za-z0-9]*\.[a-zA-Z]{2,3}$/,
message: "only email",
},
})}
type="email"
placeholder="Write Email"
/>
<span>{errors?.email?.message}</span>
<button>Add</button>
</form>
</div>
);
}
2. Custom Validation
const onValid = (data: IFormData) => {
if (data.pw !== data.pw1)
setError("pw1", {message: "pw are not same"}, {shouldFocus: true});
setError("extraError", {message: "server offline"});
};
// 코드 생략
<input
{...register("name", {
required: true,
minLength: {
value: 5,
message: "length is too short",
},
validate: {
badName: (value) =>
value.includes("fuck") ? "bad word is not allowd" : true,
},
})}
type="text"
placeholder="Write a name"
/>
<span>{errors?.name?.message}</span>
728x90