forwardRef 활용하기

justin park·2022년 9월 27일
0

React

목록 보기
1/1

react-hook-form에서 에러가 나서 forwardRef를 적용해 보았다.

  • forwardRef는 일부 컴포넌트가 수신한 ref를 받아 조금 더 아래로 전달할 수 있는 옵트인 기능이다.

  • 부모 컴포넌트에서 자식컴포넌트로 ref를 전달해 줄 일이 있을때, forwardRef를 사용하여 Props 다음의 두번째 인자로서 ref를 전달 할 수 있다.

  • ref라는 이름이 아닌 testRef이런식으로 props로 전달하면 forwardRef를 사용안해도 되지만 권장되지는 않는다.

  • 감싸고 있는 컴포넌트를 포함하도록 함수의 displayName 속성을 설정할 수도 있다.

예시

// 자식
export type Props = React.HtmlHTMLAttributes<HTMLInputElement>;

const Input = forwardRef<HTMLInputElement, Props>((props: Props, ref) => {
  return <StyledInput {...props} ref={ref} />;
});
Input.displayName = 'Input';
// 부모
const LabelInput = forwardRef<HTMLInputElement, Props>(({ label, ...rest }: Props, ref) => {  
LabelInput.displayName = 'LabelInput';
<LabelInput
	label="아이디"
    placeholder={userIdPlaceholder}
    {...register('userId', { required: true })}
/>

주의사항
컴포넌트 라이브러리에서 forwardRef를 사용하기 시작할 때 이것을 변경사항으로 간주하고 라이브러리의 새로운 중요 버전을 릴리즈 해야 한다.

profile
interested in javascript

0개의 댓글