Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add event listener to a ref?

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

like image 575
Rok Avatar asked Nov 14 '19 10:11

Rok


1 Answers

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>
    );
}
like image 51
Shubham Khatri Avatar answered Oct 18 '22 23:10

Shubham Khatri