Skip to content

Latest commit

 

History

History
39 lines (33 loc) · 1.64 KB

mergerefs.md

File metadata and controls

39 lines (33 loc) · 1.64 KB

mergeRefs

  • UI 컴포넌트를 구현할 때 React.forwardRef를 통해 전달받은 외부의 ref와 컴포넌트 자체가 보유한 ref(local ref) 모두 지원하게끔 하는 것이 일반적이다.
  • 하지만 기본적으로 리액트에서는 하나의 ref 속성에 여러 개의 ref를 설정하는 방법을 제공하지 않으므로, 유틸리티 함수를 정의해 사용한다.
import type { MutableRefObject, LegacyRef, RefCallback } from "react";

/**
 * @example
 * const Component = forwardRef((props, ref) => {
 *   const ownRef = useRef();
 *   const domRef = mergeRefs([ref, ownRef]); 
 *   return <div ref={domRef}>...</div>;
 * });
 */
 
function mergeRefs<T = any>(
  refs: (MutableRefObject<T> | LegacyRef<T>)[]
): RefCallback<T> {
  return (value) => {
    refs.forEach((ref) => {
      if (typeof ref === "function") {
        ref(value);
      } else if (ref) {
        (ref as MutableRefObject<T | null>).current = value;
      }
    });
  };
}

참고 자료