useFieldArray

굼치·2023년 9월 1일
0

react-hook-form

목록 보기
2/2

useFieldArray 언제쓸까

폼에서 동적으로 움직이는 배열이 있을때 사용하면 좋다.
예를 들어 회원 정보를 입력하는 폼에서, 연락처를 2개 이상 입력하고 싶을때 연락처 필드는 동적으로 움직이게 된다. 이럴때 useFieldArray를 사용할 수 있다.

(Ex)

function FieldArray() {
  const { control, register } = useForm();
  const { fields, append, prepend, remove, swap, move, insert } = useFieldArray({
    control, // control props comes from useForm (optional: if you are using FormContext)
    name: "test", // unique name for your Field Array
  });

  return (
    {fields.map((field, index) => (
      <input
        key={field.id} // important to include key with field's id
        {...register(`test.${index}.value`)} 
      />
    ))}
  );
}

[참고] https://www.react-hook-form.com/api/usefieldarray/

profile
마지막이라 생각하고

0개의 댓글