반응형
기본 요소에서 useRef 를 사용하는 것은 다소 어려울 수 있다. 왜냐하면 대상 요소의 타입을 지정해야만 하는데, 어떤 타입을 사용해야하는지 명확하지 않기 때문이다.
import { useRef } from "react";
const Component = () => {
// What goes here?
const audioRef = useRef<NoIdeaWhatGoesHere>(null);
return <audio ref={audioRef}>Hello</audio>;
};
간단한 해결법으로는 ref 타입에 마우스를 올리고, 어떤게 들어갈 수 있는지 체크해보는 것이 있다.

근데 더 쉬운 방법이 있다!
ElementRef 가 뭘까?
리액트에서 타입 도우미로 ElementRef를 사용할 수 있는데, ElementRef를 사용하면 대상 요소에서 타입을 쉽게 추출할 수 있다.
import { useRef, ElementRef } from "react";
const Component = () => {
const audioRef = useRef<ElementRef<"audio">>(null);
return <audio ref={audioRef}>Hello</audio>;
};
ElementRef는 forwardRef를 사용하는 커스텀 컴포넌트에서도 사용할 수 있다. ElementRef에 typeof를 전달하면, 컴포넌트가 전달하는 요소의 타입을 추출한다.
import { OtherComponent } from "./other-component";
import React, { useRef, ElementRef } from "react";
// Pass it in via typeof!
type OtherComponentRef = ElementRef<typeof OtherComponent>;
const Component = () => {
const ref = useRef<OtherComponentRef>(null);
return <OtherComponent ref={ref}>Hello</OtherComponent>;
};
만약 이전에 HTMLAudioElement 나 HTMLDivElement와 같은 방법으로 해결하고 있었으면, ElementRef로 바꿀 필요 없다. 근데 만약에 사용하는 요소의 타입이 확실치 않으면 ElementRef를 사용하는 것이 훨씬 도움된다.
참고 자료
https://www.totaltypescript.com/strongly-type-useref-with-elementref
반응형
'Front-End: Web > React.js' 카테고리의 다른 글
[React] Error: Rendered more hooks than during the previous render (0) | 2024.04.03 |
---|---|
_app와 _document (0) | 2023.07.30 |
Lazy loading을 쓸 때는 Suspense를 사용합시다! (0) | 2023.07.22 |
useRef 란? (feat. RefObject) (0) | 2023.07.22 |
useMutation 사용 시 컴포넌트 리렌더링 줄이기 (0) | 2023.07.22 |