wam
w__am 개발노트
wam
  • 분류 전체보기 (165)
    • CS 지식 (10)
      • 자료구조 (0)
      • 알고리즘 (0)
      • 컴퓨터 구조 (0)
      • 운영체제 (0)
      • 네트워크 (7)
      • 데이터베이스 (0)
      • 디자인 패턴 (3)
    • Frontend (131)
      • Three.js (64)
      • NPM (1)
      • Nest.js (19)
      • React (10)
      • Apollo (7)
      • TypeScript (2)
      • JavaScript (12)
      • HTML, CSS (1)
      • Jest (3)
      • E2E (5)
      • Cypress (7)
    • Database (12)
      • TypeORM (12)
    • IT 지식 (8)
      • 클라우드 서비스 (3)
      • 네트워크 (1)
      • 데이터 포맷 (2)
      • 기타 (2)
    • IT Book (2)
    • 유용한 사이트 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 🐱 Github

인기 글

태그

  • axeshelper
  • API
  • math.cos()
  • 함수 리터럴
  • mapped types
  • getelapsedtime()
  • 원형적인 움직임
  • 함수 표현식
  • type-graphql
  • getdelta()
  • three.js 구성 요소
  • 삼각함수
  • e.preventdefault()
  • 오프-프레미스(off-premise) 방식
  • Interface
  • gridhelper
  • joi 에러
  • Decorators
  • isabstract
  • 데이터 포맷
  • react 성능 최적화
  • threejs 개발 할 때 도움을 줄 수 있는 유틸리티
  • 함수 선언문
  • 렌더링 성능 최적화
  • 초기 환경설정
  • 디자인 패턴
  • 스코프
  • math.sin()
  • reactive variables
  • 함수의 범위

최근 글

관리자

글쓰기 / 스킨편집 / 관리자페이지
hELLO · Designed By 정상우.
wam

w__am 개발노트

[Rect Hook Form] getValues()에서 Number 타입 가져오는 법
Frontend/React

[Rect Hook Form] getValues()에서 Number 타입 가져오는 법

2024. 12. 11. 23:31
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
    'Frontend/React' 카테고리의 다른 글
    • [Rect Hook Form] 기본적으로 버튼이 submit 버튼으로 동작, 별도의 버튼 사용시 타입 지정 꼭 해주기
    • 함수를 호출하는 방식 (즉시 호출과 지연 호출)
    • React Router: push와 replace의 차이점
    • React Hook Form의 handleSubmit으로 폼 제출 시 페이지 리렌더링 방지하기
    wam
    wam

    티스토리툴바