Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React-Hook-Form 컴포넌트가 Form 태그와 분리되었을 때 Error 메세지를 출력하지 못하는 문제 #5

Open
geniee1220 opened this issue Nov 2, 2023 · 0 comments

Comments

@geniee1220
Copy link
Contributor

문제 상황

Form 태그 내 컨텐츠들을 하위 컴포넌트로 분리했을 때 하위 컴포넌트에 있는 Input 에러 메세지가 제대로 노출되지 않는 문제 발생

    // GroupRecruit - 그룹 모집 페이지 
    const {
        register,
        control,
        handleSubmit,
        formState: { errors, isValid },
      } = useForm({
        mode: 'onBlur',
      });

    return(
        <form>
            {currentStep === 1 ? ( <GroupRegistInfo />) : (<GroupRegistSchedule /> )}
        </form>
    )
    // GroupRegistInfo - 기본 정보 등록 컴포넌트 
    const {
        register,
        control,
        handleSubmit,
       formState: { errors, isValid },
      } = useForm({
        mode: 'onBlur',
      });

    return(
        <S.GroupRegistContainer>
          <Input
            inputType="input"
            label="그룹 이름 *"
            {...register('groupTitle', {
              required: '그룹 이름을 입력해주세요.',
            })}
            errors={errors}
          />
        </S.GroupRegistContainer>
)

해결 시도

Input 컴포넌트에 React-Hook-Form errors 객체가 제대로 전달되고 있는가?

로그인 및 회원가입 페이지에서 정상 작동 확인, 그룹 모집 페이지(GroupRecruit.tsx)내로 Input 컴포넌트를 위치시켰을 때는 메세지 정상 출력 확인
따라서 form 태그와 분리되었을 때 문제 발생하는 것으로 추정

useForm에 register 함수에 Input이 정상등록되고 있는가?

기본정보 등록 컴포넌트(GroupRegistInfo) 에서 엔터 이벤트 발생 시에도 form의 onSubmit 함수에 어떠한 데이터도 전달되지 않는 것을 확인
그러나 기본정보 등록 컴포넌트내에서도 register를 호출해서 등록하고 있었기 때문에, 그룹 모집 페이지에서 errors props를 내려주기 위해 코드를 수정

{currentStep === 1 ? ( <GroupRegistInfo errors={errors} />) : (<GroupRegistSchedule errors={errors} /> )}

여전히 에러 메세지를 제대로 출력하지 못하는 문제 확인

문제 해결

React-Hook-Form은 폼 데이터를 제출하는 시점에 자동으로 트리거되어 유효성 검사와 폼 제출을 실행한다. (즉 폼에 등록된 이벤트)
useForm 훅을 호출한 쪽(Form을 사용하는 컴포넌트)에서 register로 한 번만 등록해주면 된다.

// GroupRecruit - 그룹 모집 페이지 
{currentStep === 1 ? (
    <GroupRegistInfo
          register={register}
          control={control}
          errors={errors}
      />
    ) : (
   <GroupRegistSchedule />
)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant