Capturing Only Scroll Events in React
If you need to listen only to scroll events while ignoring clicks and other interactions, use React’s onScroll event.
import { useEffect, useRef } from "react";
const ScrollOnlyComponent = () => {
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleScroll = () => console.log("Scrolling...");
const element = scrollRef.current;
if (element) {
element.addEventListener("scroll", handleScroll);
}
return () => {
if (element) {
element.removeEventListener("scroll", handleScroll);
}
};
}, []);
return (
<div
ref={scrollRef}
style={{ overflowY: "scroll", height: "200px", background: "#eee" }}
>
<p style={{ height: "500px" }}>Scroll inside this box</p>
</div>
);
};
export default ScrollOnlyComponent;