Eun_Frontend
  • [React Hook Form] React Hook Form 공부 - 7 (FormValues 항목에 중첩된 객체가 있는 경우) [7/25 study]
    2024년 07월 25일 04시 28분 42초에 업로드 된 글입니다.
    작성자: 동혁이

    React Hook Form 공부 - 7

     

    FormValues 항목에 중첩된 객체가 있는 경우

    FormValues 항목에 중첩된 우리가 폼으로 입력받고 싶은 항목을 FormValues 타입으로 정의했었는데요.

    어떨 경우는 FormValues 타입에 중첩된 객체(Nested Object)를 사용해야 할 경우가 있습니다.

    이런 경우 어떻게 사용하는지 살펴보겠습니다. 코드의 간편함을 위해 password 항목을 삭제하겠습니다.

     

    type FormValues = {
      username: string;
      email: string;
      social: {
        github: string;
        twitter: string;
      };
    };
    
    export default function MyForm() {
      const {
        register,
        control,
        handleSubmit,
        formState: { errors },
      } = useForm<FormValues>({
        defaultValues: {
          username: "IU",
          email: "",
          social: {
            github: "",
            twitter: "",
          },
        },
      });
    
    ...
    ...
    }

     

    위와 같이 defaultValues를 설정했고, HTML 코드는 아래와 같이 작성합니다.

    ...
    ...
    <p>{errors.email?.message}</p>
    <label htmlFor="github">Github</label>
    <input
      type="text"
      id="github"
      {...register("social.github", {
        required: "Github account is required!",
      })}
    />
    <p>{errors.social?.github?.message}</p>
    <label htmlFor="twitter">Twitter</label>
    <input
      type="text"
      id="twitter"
      {...register("social.twitter", {
        required: "Twitter account is required!",
      })}
    />
    <p>{errors.social?.twitter?.message}</p>
    <button>Submit</button>
    ...
    ...

     

    Validation에 required를 줬습니다. 실행결과를 볼까요?

     

     

    두 번째 그림에서 콘솔창을 보면 social이란 객체가 있고, 그 안에 github, twitter 항목에 우리가 입력한 값이 잘 저장되어 있습니다.

    댓글