import { useForm } from "react-hook-form";
interface IFormProps {
name: string;
price: string; // getValues()로 가져오는 값의 타입은 기본적으로 문자열(string)
description: string;
}
const MyForm = () => {
const {
register,
getValues,
formState: { isValid, errors },
handleSubmit
} = useForm<IFormProps>({
mode: "onChange",
});
const onSubmit = (data: IFormProps) => {
const { name, price, description } = getValues();
createDishMutation({
variables: {
input: {
name,
price +price, // +price : 형변환 (string -> number)
description,
restaurantId: +restaurantId
}
}
});
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...register("price", {
required: "가격을 입력해 주세요.",
min: {
value: 0,
message: "가격은 0 이상이어야 합니다.",
},
})}
className="input"
type="number"
placeholder="가격"
/>
<button type="submit">제출</button>
</form>
);
};
export default MyForm;
- React Hook Form에서 getValues()로 가져오는 값의 타입은 기본적으로 문자열(string)이다.
- 이는 HTML 폼 요소(<input>)가 값을 문자열로 반환하기 때문이다.
- 심지어 type="number"로 설정된 <input>에서도 반환값은 문자열로 처리된다.
valueAsNumber 옵션 사용하여 숫자로 자동 변환하기
import { useForm } from "react-hook-form";
interface IFormProps {
name: string;
price: number; // number 타입
description: string;
}
const MyForm = () => {
const {
register,
getValues,
formState: { isValid, errors },
handleSubmit
} = useForm<IFormProps>({
mode: "onChange",
});
const onSubmit = (data: IFormProps) => {
const { name, price, description } = getValues();
createDishMutation({
variables: {
input: {
name,
price,
description,
restaurantId: +restaurantId
}
}
});
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...register("price", {
required: "가격을 입력해 주세요.",
valueAsNumber: true, // 값을 숫자로 변환
min: {
value: 0,
message: "가격은 0 이상이어야 합니다.",
},
})}
className="input"
type="number"
placeholder="가격"
/>
<button type="submit">제출</button>
</form>
);
};
export default MyForm;
'Frontend > React' 카테고리의 다른 글
[Rect Hook Form] 기본적으로 버튼이 submit 버튼으로 동작, 별도의 버튼 사용시 타입 지정 꼭 해주기 (0) | 2024.12.12 |
---|---|
함수를 호출하는 방식 (즉시 호출과 지연 호출) (0) | 2024.12.12 |
React Router: push와 replace의 차이점 (0) | 2024.10.15 |
React Hook Form의 handleSubmit으로 폼 제출 시 페이지 리렌더링 방지하기 (0) | 2024.09.26 |
React Router v6 (0) | 2024.09.26 |