reactrefforwardref
React ref와 forwardRef - DOM 접근과 컴포넌트 간 ref 전달
조회 0
React에서 DOM 요소에 직접 접근하거나, 자식 컴포넌트의 메서드를 호출할 때 ref를 사용합니다.
이 글에서는 useRef, forwardRef, useImperativeHandle의 사용법과 실무 패턴을 정리합니다.
1. useRef 기본 사용법
function TextInput() {
const inputRef = useRef<HTMLInputElement>(null);
const focusInput = () => {
inputRef.current?.focus();
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>포커스</button>
</>
);
}
ref.current는 DOM 요소나 컴포넌트 인스턴스를 가리킵니다.null로 초기화하고, 마운트 후에 값이 할당됩니다.
2. forwardRef로 ref 전달
함수 컴포넌트는 기본적으로 ref를 받을 수 없으므로, forwardRef로 래핑해야 합니다.
const CustomInput = forwardRef<HTMLInputElement, { label: string }>(
({ label }, ref) => {
return (
<label>
{label}
<input ref={ref} type="text" />
);
}
);