How can I add an event listener to the ref
using ReactJS Hooks (version 16.8. +)?
Here is an example where I tried to get the scroll position of certain div with overflow-auto. updateScrollPosition
never gets called.
function Example(props) {
scroller = useRef();
useEffect(() => {
function updateScrollPosition() {
// update the scroll position
}
if (scroller && scroller.current) {
scroller.current.addEventListener("scroll", updateScrollPosition, false);
return function cleanup() {
scroller.current.removeEventListener("scroll", updateScrollPosition, false);
};
}
});
return (
<div ref={scroller}>
<div className="overflow-auto">
some text
</div>
</div>
);
}
I appreciate your help
The problem is that your your outer-div wouldn't be scrolling, instead our inner div will have scroll and hence scroll
event isn't triggered on the outer div. Change your ref to be on the inner div and it should work
function Example(props) {
const scroller = useRef();
useEffect(() => {
function updateScrollPosition() {
// update the scroll position
}
if (scroller && scroller.current) {
scroller.current.addEventListener("scroll", updateScrollPosition, false);
return function cleanup() {
scroller.current.removeEventListener("scroll", updateScrollPosition, false);
};
}
}, []);
return (
<div>
<div ref={scroller} className="overflow-auto">
some text
</div>
</div>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With