[React] Hook - useForm

eslim·2020년 10월 18일
0
post-thumbnail

이번 프로젝트 결제 페이지에서 사용하게 된 useForm

1. useForm

  • React Hook Form 으로 간단하게 폼의 유효성을 검사하기

설치

npm install react-hook-form

import

import { useForm } from "react-hook-form";
import { ErrorMessage } from "@hookform/error-message";
  • errormessage 구현

js 기능 구현

const { register, errors, handleSubmit } = useForm();

const onSubmit = (data) => {
    console.log("data", data);
    console.log("m", ErrorMessage);
  };

  

결제 페이지

const { register, errors } = useForm();

<InfoBox>
  {USERBILL.map((userData, idx) => {
    return (
      <UserBillBox key={idx}>
      <label>{userData.title}</label>
		<input
          type={userData.type}
          name={userData.name}
          ref={register({ required: true })}
          />
               <ErrorMessage
               errors={errors}
name={userData.name}
message={userData.message}
as="p"
/>
  </UserBillBox>
);
})}
</InfoBox>
        
           

Mock data 활용


const USERBILL = [
  {
    id: 1,
    title: "Country / Region *",
    name: "country",
    type: "text",
    required: true,
    message: "Country / Region field is required.",
  },
  ...
]

export default USERBILL

useForm 장점

  • 리액트 훅(React Hook) 사용 시 이러한 복잡한 코드를 컴포넌트가 아닌 함수로 분리해낼 수 있게 되어 양식 컴포넌트를 구현하는 것이 훨씬 간편해졌다.

0개의 댓글