How to Implement Reveal on Scroll in React using the Intersection Observer API
Sun Mar 26 2023 17:11:08 GMT+0000 (Coordinated Universal Time)
Saved by
@vishalbhan
#javascript
import "./App.css";
import { useState, useRef, useEffect } from "react";
function App() {
const [isIntersecting, setIsIntersecting] = useState(false);
const ref = useRef(null);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
setIsIntersecting(entry.isIntersecting);
},
{ rootMargin: "-300px" }
);
console.log(isIntersecting);
observer.observe(ref.current);
return () => observer.disconnect();
}, [isIntersecting]);
useEffect(() => {
if (isIntersecting) {
ref.current.querySelectorAll("div").forEach((el) => {
el.classList.add("slide-in");
});
} else {
ref.current.querySelectorAll("div").forEach((el) => {
el.classList.remove("slide-in");
});
}
}, [isIntersecting]);
return (
<div className="App">
<header>This is the Header</header>
<main ref={ref}>
<div className="child-one">Child One</div>
<div className="child-two">Child Two</div>
</main>
<footer>This is the Footer</footer>
</div>
);
}
export default App;
content_copyCOPY
https://www.freecodecamp.org/news/reveal-on-scroll-in-react-using-the-intersection-observer-api/
Comments