문제 상황
.tsx에서 아래의 코드 input의 “ref”에 빨간색이 나타나며 마우스를 오버하면 에러 문구가 나타났다.
import { useRef } from "react";
export default const UserSearch: React.FC = () => {
const inputRef = useRef();
return (
<div>
User Search
// 아래 ref에 오류 표기
<input ref={inputRef} />
</div>
);
};
에러 문구
Type ‘MutableRefObject' is not assignable to type 'LegacyRef | undefined'. Type 'MutableRefObject' is not assignable to type 'RefObject'. Types of property 'current' are incompatible. Type 'undefined' is not assignable to type 'HTMLInputElement | null'.ts(2322) index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<InputHTMLAttributes, HTMLInputElement>'
해결 방안
아래와 같이 “<HTMLInputElement | null>”를 추가하고, 기본값을 null로 추가하면 에러가 해결된다.
import { useRef } from "react";
export default const UserSearch: React.FC = () => {
// 아래의 코드 블럭에 타입 정의
const inputRef = useRef<HTMLInputElement | null>(null);
return (
<div>
User Search
<input ref={inputRef} />
</div>
)
이유
- “HTMLInputElement” 타입을 정의한 이유 : ref는 DOM을 직접 조작하는 hook이다. 따라서 Typescript 사용시, input 타입을 정의가 필요하다.
- “null”을 타입과 기본값으로 정의한 이유 : 처음 컴포넌트가 랜더링이 되었을 때 ref가 생성된다. 이때 어떠한 값도 들어가 있지 않기에 null을 추가해야한다. 또한, 해당 input을 사용자가 전혀 사용하지 않을 가능성이 있기에 null을 기본값으로 추가 해야한다.
결론은 “HTMLInputElement”은 고객이 input을 사용하는 시점, “null”은 Component가 초기 랜더링 되어 아무런 값이 없는 시점을 위해 모두 정의되어야 한다.
'React' 카테고리의 다른 글
[React] Rendering은 어떻게 동작할까? (2/3) - Render 단계 (1) | 2024.02.15 |
---|---|
[React] Render의 진짜 의미와 동작 원리 (1/3) - Overview (0) | 2024.02.12 |
[React] Component가 Instance, Element로 변화는 과정 (0) | 2024.02.08 |
[React] useMemo를 사용한 화면 깜빡거림 제거 (0) | 2024.01.09 |