[React] 스크롤 여부 동적으로 파악하기

jellyjw·2024년 9월 3일
0
post-thumbnail

스크롤 여부에 따라 처리를 해줘야 할 때, 동적으로 스크롤 여부를 파악할 수 있는 방법이다.

  const containerRef = useRef<null | HTMLDivElement>(null);


	<div
        ref={containerRef}
        className="flex w-full space-x-4 overflow-x-scroll pb-[0.5rem]"
      >
        {imageList.map((image, index) => (
          <img
            src={`${CDN}/posts/${image}`}
            alt={`Slide ${index}`}
          />
        ))}
   </div>

리스트의 컨테이너에 ref를 할당해주고,

  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      setHasScroll(container.scrollWidth > container.clientWidth);
    }

    if (imageList.length === 0) {
      setHasScroll(false);
    }
  }, [imageList]);

container의 scrollWidth 보다 clientWidth 가 크면 state를 true로 변경해 주었다.

profile
남는건 기록뿐👩🏻‍💻

0개의 댓글