I am trying to execute a function when an element is visible in the viewport but the callback is running even if the element is wayyy below.
this is App.jsx
import {useState,useEffect,useRef} from 'react';
import Rect from "./Rect.jsx"
export function App(props) {
const [rects,setRects]=useState([])
const refer=useRef(null)
const observer=useRef()
useEffect(()=>{
for (let i=0;i<50;i++){
(i!==40)?setRects((reacts)=>[...reacts,<Rect index={i}/>]):setRects((reacts)=>[...reacts,<Rect index={i} ref={refer}/>])
}
observer.current=new IntersectionObserver((data)=>{
alert(data[0].isIntersecting)
},{threshold:1})
},[])
//I have found a workaround by just doing this and have no dependency array
//observer.current=new IntersectionObserver((data)=>{
// if (data[0].isIntersecting)
// alert(data[0].isIntersecting)
//},{threshold:1})
useEffect(()=>{
if (refer.current){
observer.current.observe(refer.current)
}
})
//},[])
// if you put an empty array here then the callback isnt run even if the element is visible
return (
<div className='App'>
<h1>Hello React.</h1>
{rects.map((rect)=>rect)}
</div>
);
}
this is Rect.jsx
import { forwardRef } from "react";
const Rect=forwardRef((props,ref)=>{
return (props.index==40)? <div style={{backgroundColor:"red",height:"20px",width:"20px"}} ref={ref}> </div>:<div style={{backgroundColor:"black",height:"20px",width:"20px"}}> </div>
})
export default Rect
I have found the way to get it to work as i want but i don’t know if its correct way and i want to know why is it behaving the way it is
playground