How about this ?
codesandbox: https://codesandbox.io/s/withered-sound-rkokr9
You can check the console, it only printout value on horizontal scroll.
import { useEffect } from "react";
import "./styles.css";
export default function App() {
useEffect(() => {
var ticking = false;
var lastScrollLeft = 0;
const onScroll = () => {
if (!ticking) {
window.requestAnimationFrame(function () {
var documentScrollLeft = window.scrollX;
if (lastScrollLeft != documentScrollLeft) {
console.log(
"only scroll x, lastScroll: ",
lastScrollLeft,
" documentScrollNow",
documentScrollLeft
);
lastScrollLeft = documentScrollLeft;
}
ticking = false;
});
ticking = true;
}
};
window.addEventListener("scroll", onScroll);
return () => {
window.removeEventListener("scroll", onScroll);
};
}, []);
return (
<div className="App" style={{ width: "300vw", height: "150vh" }}>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
From the related article, I change window.scrollLeft
to window.scrollX
, this has some issue. scrollLeft
is for IE.
Add window.addEventListener()
inside useEffect so it doesn't get runned again every state changed, and onunmount which is return () => {}
callback, we remove the eventlistener.
// UPDATE
Solution for your table onScroll
codesandbox: https://codesandbox.io/s/festive-silence-xuwfl2
maybe something like this.