본문 바로가기
React

[React] 'ref.current' is possibly 'null'.

by lvd-hy 2023. 7. 14.
반응형

 

목차

     

    1. 에러 상황

    typeScript를 사용하는 프로젝트 진행 시 상품리스트 중 상단에 추천 상품 영역 슬라이드를 구현하기 위해 useRef로 DOM에 접근하러 했으나, 'ref.current' is possibly 'null'. 와 같은 에러가 발생하였다.

    ⬇️구현할 기능 : 양쪽 화살표 클릭 시 다른 상품을 보여주기

    2. 해당 코드 부분

    import React, { useState, useEffect, useRef } from "react";
    
    const ref = useRef<HTMLDivElement>(null);
    
    const handlePrev = () => {
        if (ref.current.style.transform === "translateX(0px)") {
          return;
        } else {
          setTranslate(translate + 440);
        }
      };
    
      const handleNext = () => {
        const productCnt = data.length;
        if (
          ref.current.style.transform === `translateX(-${(productCnt - 4) * 220}px)`
        ) {
          return;
        } else {
          setTranslate(translate - 440);
        }
      };
      
      <S.ProductsBox>
      <S.ArrowLeftIcon onClick={handlePrev} />
      <S.ProductsCarousel>
        {!recommendData.length ? (
          <S.EmptyProduct>상품 정보가 없습니다.</S.EmptyProduct>
        ) : (
          <></>
        )}
        {recommendData.map((recommendData) => (
          <S.Product ref={ref} style={{ transform: `translateX(${translate}px)` }}>
            <ProductItemRecommend
              url={`${IMG_URL}/${recommendData.imageLink}`}
              isSell={false}
              like={recommendData.isLike}
              title={recommendData.name}
              price={recommendData.price}
              productId={recommendData.productId}
            />
          </S.Product>
        ))}
      </S.ProductsCarousel>
      <S.ArrowRightIcon onClick={handleNext} />
    </S.ProductsBox>;

    3. 원인

    TypeScript는 ref.current가 null일 수 있음을 확인하고 오류를 발생시킨다.

    4. 해결방법

    null 검사를 수행하는 로직을 추가해주자!

    const handlePrev = () => {
        if (ref.current) { // null 체크
          if (ref.current.style.transform === "translateX(0px)") {
            return;
          } else {
            setTranslate(translate + 440);
          }
        }
      };
    
      const handleNext = () => {
        const productCnt = data.length;
        if (ref.current) { // null 체크
          if (
            ref.current.style.transform ===
            `translateX(-${(productCnt - 4) * 220}px)`
          ) {
            return;
          } else {
            setTranslate(translate - 440);
          }
        }
      };

    Reference

    https://atomizedobjects.com/blog/react/how-to-use-useref-with-typescript/

     

    How to use useRef with TypeScript

    Discover how to use useRef with TypeScript in React and React native, and how to fix issues with MutableRefObject and object is possibly 'null'.

    atomizedobjects.com

     

    반응형

    'React' 카테고리의 다른 글

    [React] Proxy와 Proxy 사용법  (0) 2023.06.07
    [React] 특징과 JSX 문법  (1) 2023.04.27
    [React] 리액트에서 아이콘 사용하기  (0) 2023.03.27
    [React] React 시작하기  (0) 2023.03.24

    댓글