I want to make an "Intersection Observer" for my project that I created with React. From what I've researched on the internet, I think I followed all the instructions correctly. But my code doesn't work, I don't understand where is the error. Can you help me please ?
My react project code;
import './App.css';
import Header from './components/Header'
import HeroImage from './components/HeroImage'
import Hakkimizda from './components/Hakkimizda'
import UrunGalerisi from './components/UrunGalerisi'
import Sss from './components/sss'
import Footer from './components/Footer'
import { useRef, useState, useEffect } from 'react';
function App() {
//Variables
const containerRef = useRef(null);
const [isVisible, setIsvisible] = useState(false);
//callbackFunction
const callBackFunction = (entries)=>{
const [entry] = entries;
setIsvisible(entry.isIntersecting);
}
//Options
const options = {
root:'null',
rootMargin:'0px',
treshold:1.0
}
//useEffect
useEffect(()=>{
const observer = new IntersectionObserver(callBackFunction, options)
if(containerRef.current) observer.observe(containerRef.current)
return ()=>{ if(containerRef.current) observer.unobserve(containerRef.current) }
}, [containerRef, options])
return (
<div className="App">
<Header />
<HeroImage />
<Hakkimizda />
<UrunGalerisi />
<Sss />
<Footer />
</div>
);
}
export default App;
the error I get is;
CodePudding user response:
You have to attach the containerRef
to the DOM element you want to observe, with something like :
<div ref={containerRef}>foo</div>
CodePudding user response:
@krirkrirk
I added like this but nothing changed;
return (
<div ref={containerRef} className="App">
<Header />
<HeroImage />
<Hakkimizda />
<UrunGalerisi />
<Sss />
<Footer />
</div>
);
}
export default App;