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 지정 및 필요한 처리를 할 수 있다