스크롤 내릴 때 다음 섹션 보여주기

임성은·2023년 4월 12일
0

포트폴리오를 어떻게 구성하면 좋을지 서치 중 스크롤을 조금만 내렸는데
다음 섹션을 바로 보여주는 기능을 겪어보니 오..나도! 라는 생각이 들어 바로 구현해보았습니다..

"IntersectionObserver"

처음 사용해 보는 기능인데 사실 전부터 사용해보고 싶다고 느꼈습니다.
(코딩애플 선생님의 유튜브에서 한번 소개가 되었습니다..)

스크롤 이벤트에서 유용하게들 사용하는데 주로 무한스크롤에서 자주 사용됩니다. IntersectionObserver 는 브라우저에 내장된 API로 관찰?감시하는 기능으로 무한스크롤 외에도
레이지 로딩(Lazy Loading)으로 특정 콘텐츠를 나타나게 할 때도 쓰입니다.

IntersectionObserver의 생성자는 두 개의 인자를 받습니다.

  • 첫 번째 인자는 콜백 함수입니다. 이 함수는 관찰 대상 요소들의 상태가 변화할 때마다 호출됩니다.
  • 두 번째 인자는 options 객체로, threshold 프로퍼티를 가질 수 있습니다. threshold는 교차영역의 비율을 나타내며, 제 코드에선 값이 0.5(절반) 이상일 때 콜백 함수가 호출됩니다.
const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.intersectionRatio >= 0.5) {
            animateScroll.scrollTo(entry.target.offsetTop, { duration: 400 });
          }
        });
      },
      { threshold: 0.5 }
    );

✨ animateScroll.scrollTo(entry.target.offsetTop, { duration: 400 })
리액트 스크롤 라이브러리를 사용하여 해당 섹션 = entry.target의 상단으로 스크롤이 이동.


💫 전체코드

  useEffect(() => {
    const sectionIds = ['section1', 'section2', 'section3', 'section4'];

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.intersectionRatio >= 0.5) {
            animateScroll.scrollTo(entry.target.offsetTop, { duration: 400 });
          }
        });
      },
      { threshold: 0.5 }
    );

    sectionIds.forEach((id) => {
      const section = document.getElementById(id);
      observer.observe(section);
    });

   
  }, []);
profile
개발자의 길에 당차게 들어서다!!

0개의 댓글