[react-intersection-observer] Array.prototype.map() 메서드를 이용하여 생성한 여러 컴포넌트 스크롤 감지 처리 (InView)

나라·2024년 5월 10일

Trouble Shooting

목록 보기
12/14

개요

  • 여태껏 intersection observer 을 이용한 스크롤 애니메이션 기능을 처리할 때는 useInView 를 이용하여 작업
import { useInView } from "react-intersection-observer";
const { ref, inView} = useInView({
    threshold: 0.33,
  });
  • 하지만 하나의 컴포넌트가 아니고 예를 들어 여러 컴포넌트에 지정해야한다면?
  const { ref: ref1, inView: inView1} = useInView({
    threshold: 0.33,
  });
  const { ref: ref2, inView: inView2 } = useInView({
    threshold: 0.33,
  });
  const { ref: ref3, inView: inView3 } = useInView({
    threshold: 0.33,
  });
.
.
.
  • 비효율적+코드가 길어질 뿐더러 컴포넌트 개수마다 각각 지정할 수도 없는 노릇

  • 심지어 Array.prototype.map() 메서드를 사용해 컴포넌트 생성 시에는

const { ref, inView } = useInView();

      <ul>
        {solutionList.map((item) => (
          <li key={item.id} ref={ref} className={clsx(inView && "isViewed")}>
				....
          </li>
        ))}
      </ul>

위와 같은 코드는 당연히 오류가 난다

해결

살펴보니 공식문서를 살펴보면 (기존에 주로 사용하던 방식인) useInView 외에 InView 컴포넌트를 이용한 방식도 설명하고 있다

import { InView } from "react-intersection-observer";

<ol>
    {aiServiceList.map((item) => (
      <InView key={item.id} threshold={0.5} triggerOnce={true}>
      {({ inView, ref }) => (
        <li ref={ref} className={inView ? "show" : ""}>
        ...
        </li>
  	)}
    </InView>
  ))}
  </ol>

이런 식으로 작업하면 map() 메서드를 이용하여 생성되는 컴포넌트마다 ref 지정 및 필요한 처리를 할 수 있다

끄읕

profile
FE Dev🔥🚀

0개의 댓글