
npm install react-hook-form으로 설치onChange, onBlur, name을 갖음 register('test.0.firstName'); // ✅
register('test[0]firstName'); // ❌
readOnly 또는 전체 fieldset을 disable시키기 (예 : 예제)| Name | Type | Description |
|---|---|---|
| name | string | 등록될 input name |
| onChange | ChangeHandler | input change 이벤트 발생을 subscribe하는 prop |
| onBlur | ChangeHandler | input에 blur 이벤트 발생을 subscribe하는 prop |
| inputName | Submit Result |
|---|---|
| register("hi") | {hi : input값} |
| register("Hi.hello") | {Hi : {Hello : input값}} |
| register("Hi.hello.0") | {Hi : {Hello : [input값]}} |
| Name | Description | Code Example |
|---|---|---|
| ref | React element ref | <input {...register("test")} /> |
| required | true이면 submit전에 input값을 가져야하며 errors객체를 이용하여 error message를 할당 가능 | <input {...register("test", { required: 'error message'}})}/> |
| maxLength | input 값 최대길이 | <input{...register("test", { maxLength : { value: 2, message: 'error message' }})}/> |
| minLength | input값 최소 길이 | <input{...register("test", { minLength : { value: 1, message: 'error message' }})}/> |
| max | input에 들어올 수 있는 최대값 | <input type="number" {...register('test', { max: { value: 3, message: 'error message' } })} /> |
이 외 여러가지는 공식문서를 참고 하면 좋을 듯 하다
링크 : hook-form/register
에러메세지는 JS에서는 p태그, TS는 string을 지원
이메일 정규화식
const onSubmit = async () => {
try {
} catch(e) {
}
};
| Name | Type | Description |
|---|---|---|
| SubmitHandler | (data : Object, e?:Event) => Promise | success callback |
| SubmitErrorHandler | (errors:Object, e?:Event) => Promise | error callback |
const onSubmit = (data: object) => {
console.log(data);
};
const onInvalid = (errors: object) => {
// required가 만족하지 않거나 하면 errorHandler로 들어옴
console.log(errors);
};
<form onSubmit={handleSubmit(onSubmit, onInvalid)}>
</form>
| Type | Description |
|---|---|
| string | watch input value by name |
| string[] | watch multiple inputs |
| undefined | watch all inputs |
| (data:unknown, {name : string, type :string}) => void | watch all inputs and invoke a callback |
import React from "react"
import { useForm } from "react-hook-form"
interface IFormInputs {
name: string
showAge: boolean
age: number
}
function App() {
const {
register,
watch,
formState: { errors },
handleSubmit,
} = useForm<IFormInputs>()
const watchShowAge = watch("showAge", false) // you can supply default value as second argument
const watchAllFields = watch() // when pass nothing as argument, you are watching everything
const watchFields = watch(["showAge", "age"]) // you can also target specific fields by their names
// Callback version of watch. It's your responsibility to unsubscribe when done.
React.useEffect(() => {
const subscription = watch((value, { name, type }) =>
console.log(value, name, type)
)
return () => subscription.unsubscribe()
}, [watch])
const onSubmit = (data: IFormInputs) => console.log(data)
return (
<>
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("name", { required: true, maxLength: 50 })} />
<input type="checkbox" {...register("showAge")} />
{/* based on yes selection to display Age Input*/}
{watchShowAge && (
<input type="number" {...register("age", { min: 50 })} />
)}
<input type="submit" />
</form>
</>
)
}
const {
register, //input 할당, value 변경 감지
handleSubmit, // form submit될 때 호출
formState: { errors }, // 폼상태 객체, errors값이 들어있음
watch, // 특정한 폼 필드의 값을 실시간으로 사용
} = useForm();
<input
type="text"
placeholder="username"
//name="username"으로 썼었는데 이걸 register에 명시해주는것
//뒤에는 객체형태로 옵션넣어주면된다
//오류 메세지도 지정가능
{...register('username', {
required: '이름을 입력해주세요.',
minLength: {
message: '이름은 최소 2글자 이상 작성해주세요.',
value: 2,
},
})}
/>
{errors.username?.message}
//?는 있으면 실행 없으면 실행하지 않는 다는 의미를 뜻함.
hook-form에 대해서 스치듯 지나갔는데 이렇게 다시 복습하니까 조오금 알 것도 같다. 이제 이걸 가지고 작은 component를 만들어 사용하는 것을 작성할 예정이다. react는 대충 깔짝거려서 만들수도, 정말 공부를 많이 하고서 이런 저런 다양한 활용을 할수도 있는 것 같다. 그동안 방황한거 만회하려면 열심히 공부해서 열심히 블로깅해야지. 리액트는 정말 많이 공부해야하는게 느껴지니까..! 찾아보고 정리하고 적용하고 발전시키고 재밌다!
참고 : 코딩온 교안 , react-hook-form 공식 문서