본문 바로가기

Front-End: Web/React.js

"ElementRef"로 useRef 타입을 더 강력하게 지정하기

반응형

기본 요소에서 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

반응형