Framework/React

[React] typescript useRef ์‚ฌ์šฉ์‹œ undefined / null ์˜ค๋ฅ˜ ๋ฐœ์ƒ ์›์ธ ๋ฐ ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•

yuri lee 2023. 3. 29. 22:54
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” react ์—์„œ useRef ์‚ฌ์šฉ์‹œ undefined / null ์˜ค๋ฅ˜ ๋ฐœ์ƒ ์›์ธ๊ณผ ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. ์šฐ์„  ์ œ๊ฐ€ useRef๋ฅผ ์‚ฌ์šฉํ•œ ์ฝ”๋“œ ์˜ˆ์ œ๋Š” ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค. clientHeight๋ฅผ ์กฐ์ ˆํ•˜๊ธฐ ์œ„ํ•ด useRef๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ div tag์— ์ ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. 

const divRef = useRef<HTMLDivElement>(null);
const [handlePosition, setHandlePosition] = useState('300vh');

useEffect(() => {
   setHandlePosition(`${(divRef.current.clientHeight * 3) / 300}px`);
}, []);

return (
    <div ref={divRef}>
        {/* some content */}
    </div>
);

 

ํ•˜์ง€๋งŒ, ํ•ด๋‹น ์ฝ”๋“œ๋ฅผ ์‹คํ–‰์‹œ undefined ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค. 

 

TS2532: Object is possibly 'undefined'.

 

Why?

ํ•ด๋‹น ์—๋Ÿฌ๋Š” divRef.current ๊ฐ’์ด undefined์ผ ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐœ์ƒํ•˜๋Š” ์—๋Ÿฌ์ž…๋‹ˆ๋‹ค. ํ˜„์žฌ ์ฝ”๋“œ์—์„œ ์ด ๊ฐ’์ด null์ด ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๊ณ , ์ด ๊ฒฝ์šฐ์— divRef.current.clientHeight ์—์„œ undefined๊ฐ€ ๋ฐ˜ํ™˜๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

 

์œ„ ์˜ค๋ฅ˜๋Š”  ์•ฝ 2๊ฐ€์ง€ ๋ฐฉ๋ฒ•์œผ๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

 

How to solve the problem

#1 null ์ฒดํฌํ•˜๊ธฐ

divRef.current ๊ฐ’์ด null์ด ์•„๋‹ ๋•Œ๋งŒ setHandlePosition ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋„๋ก ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

useEffect(() => {
    if (divRef.current) {
        setHandlePosition(`${(divRef.current.clientHeight * 3) / 300}px`);
    }
}, []);

 

#2 ์˜ต์…”๋„ ์ฒด์ด๋‹ ์—ฐ์‚ฐ์ž(?) ์‚ฌ์šฉ

useEffect(() => {
    if (divRef.current) {
        setHandlePosition(`${(divRef.current.clientHeight * 3) / 300}px`);
    }
}, []);

 

๋ฐ˜์‘ํ˜•