React
react useRef 에러 TS2322 MutableRefObject<undefined>
min.js
2024. 1. 30. 10:00
반응형
react useRef 사용하면서 자주 겪는 에러 TS2322 MutableRefObject<undefined> 해결방법
useRef를 사용하고 나니 아래와 같은 에러와 함께 빨간줄이 그어졌다..
Type 'MutableRefObject<undefined>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<HTMLDivElement>'.
Types of property 'current' are incompatible.
Type 'undefined' is not assignable to type 'HTMLDivElement | null'.ts(2322)
index.d.ts(125, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>,
찾아보니 useRef 선언시에 null을 빼먹어서 생기는 에러였다.
// ❌ ❌ ❌
const boxRef = useRef();
// ✅ ✅ ✅
const boxRef = useRef(null);
해결 완료!!
반응형