react-hook-form 사용중 ref 오류 및 해결방법

크롱·2023년 9월 20일
0

PLAY-LAB 프로젝트

목록 보기
1/1
post-thumbnail

기존오류코드

export default function NumberInput({ unit, id, type, onInput }) {
	return (
      <S.Flex>
      <S.NumberInput id={id} type={type} onInput={onInput}></S.NumberInput>
      <S.Unit>{unit}</S.Unit>
      </S.Flex>
	)}


------------------------------------------------------------------------
import NumberInput from '../../components/Product/NumberInput'

<NumberInput
       unit="개"
       id="stock"
       type="text"
       onInput={blockTextInput}
      {...register('stock', {
       required: '* 재고는 필수 입력입니다.',
})}
/>


프로덕트 업로드 사이트에 숫자를 입력하는 input을 NumberInput이란 컴포넌트로 만들어서, page에 import 해왔는데, ref 오류가 발생했다.

import해왔기때문에 함수형 컴포넌트가 ref를 직접적으로 받을 수 없기 때문에 발생하는 문제이다.

해결방법
forwardRef를 사용하여 접근
register 부분도 props전달처럼 해줘야함.



완성코드

import React, { forwardRef } from 'react'

import * as S from './NumberInput.style'

const NumberInput = forwardRef(({ unit, id, type, register, onInput }, ref) => {
  return (
    <S.Flex>
      <S.NumberInput
        id={id}
        type={type}
        ref={ref}
        onInput={onInput}
        {...register}
      ></S.NumberInput>
      <S.Unit>{unit}</S.Unit>
    </S.Flex>
  )
})

export default NumberInput
<NumberInput
     unit=""
     id="stock"
     type="text"
     onInput={blockTextInput}
     register={register('stock', {
      required: '* 재고는 필수 입력입니다.',
     })}
/>
profile
👩‍💻안녕하세요🌞

0개의 댓글