reactjsinview

How to on being able to see on Viewport change The text


i am trying to on View change the text depending on which image being shown, like each img has its own description as i toggle on each image.

const [ObserveVis, setObserveVis] = useState()

useEffect(() => {
  const observer = new IntersectionObserver ((entries) => {
    const entry = entries[0];
    setObserveVis(entry.isIntersecting)
  })
  observer.observe(carouselRef.current)
},[])

i have this to log the ref container

<div ref={carouselRef} >
  {ProjectImg.map((img, index) => (
    <div key={index} >
      <img ref={imgRef1} onClick={() => window.open("https://snazzy-meerkat-f90f61.netlify.app/")} src={img} alt="My Project Image" />
       </div>
                    ))}
  </div>
                  
 <button onClick={scrollToPrevItem}>Prev</button>
 <button onClick={scrollToNextItem}  >Next</button>
     </div>
   </div>
      <p >{ObserveVis ? 'yes' : 'Nah'}</p>

If you explain what i be the next step id appreciate it


Solution

  • Here is my code

    1. You will need an additional state to trach which image (and its corresponding description) is currently being viewed.

    const [currentIndex, setCurrentIndex] = useState(0);
    const descriptions = [
      "Image Description1",
      "Image Description2",
      "Image Description3",
    ];

    1. And update the index on image change

    //Scroll to next item
    setCurrentIndex(prevIndex => (prevIndex + 1) % ProjectImg.length);
    //Scroll to previous item
    setCurrentIndex(prevIndex => (prevIndex - 1 + ProjectImg.length) % ProjectImg.length);

    1. Track current Visible Image

    //Update useEffect 
    useEffect(() => {
      const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            setCurrentIndex(Number(entry.target.getAttribute('data-index')));
          }
        });
      }, { threshold: 0.5 });
    
      document.querySelectorAll('.carousel-item').forEach((item, index) => {
        item.setAttribute('data-index', index);
        observer.observe(item);
      });
    
      return () => observer.disconnect();
    }, []);

    1. Display the current image descirption

    <p>{descriptions[currentIndex]}</p>