React에서 Scroll Event 감지하기

상현·2023년 12월 28일
1

React

목록 보기
17/24

페이지에서 상단으로 바로 이동할 수 있는 Top 버튼을 만들어야 했는데, 스크롤이 어느정도 내려갔을 때 버튼이 보이게 하면 좋겠다는 생각을 했다.

이를 위해 같이 코드를 작성을 했다.

1. 위로 스크롤 하는 함수 작성

// behavior를 인자로 받아서 맨 위로 스크롤 해준다.
const handleScrollToTop = (behavior: 'smooth' | 'auto') => {
  window.scrollTo({top: 0, behavior: behavior});
};

2. useEffect 안에서 addEventLister 사용

useEffect(() => {
  // 페이지가 렌더링 되면 무조건 맨위로 스크롤 한다.
  handleScrollToTop('auto');
 
  const handleScroll = () => {
    // 일정 구간 스크롤이 내려가면 버튼을 보여준다.
    if (window.scrollY > window.outerHeight / 3) setShowTopButton(true);
    else setShowTopButton(false);
  };

  // window에 scroll 이벤트를 넣는다.
  window.addEventListener('scroll', handleScroll);

  // 페이지를 벗어날 때 이벤트를 제거한다.
  return () => {
    window.removeEventListener('scroll', handleScroll);
  };
  
}, []);

3. debouncing 적용

useEffect(() => {
  handleScrollToTop('auto');
  
  // timer 생성
  let timer: number | null = null;

  const handleScroll = () => {
    
    // 디바운싱 구현
    if (timer) {
      clearTimeout(timer);
    }
    
    timer = window.setTimeout(() => {
      if (window.scrollY > window.outerHeight / 3) setShowTopButton(true);
      else setShowTopButton(false);
    }, 100);
  };

  window.addEventListener('scroll', handleScroll);

  return () => {
    window.removeEventListener('scroll', handleScroll);
  };
}, []);

결과

profile
프론트엔드 개발자 🧑🏻‍💻 https://until.blog/@love

0개의 댓글