use-scroll-position: How to make it work with an inner container that has overflow auto?

For reference, here is a codesandbox.

I have a div, which has content that is bigger than the div’s size. Therefore I made it scrollable using overflow: auto. My question is, how can I track this divs scroll position?

I tried doing this:

export default function App() {
  const divRef = useRef();
  useScrollPosition(
    ({ currPos }) => {
      console.log(currPos); // never logs out, cause scroll progress of `div` isn't tracked
    },
    [],
    divRef,
    false,
    300
  );

  return (
    <div className="App">
      <div
        ref={divRef}
        style={{
          backgroundColor: "blue",
          overflowY: "auto",
          padding: "5px",
          height: "300px"
        }}
      >
        <div
          style={{
            backgroundColor: "red",
            height: "2000px"
          }}
        />
      </div>
    </div>
  );
}

But this ref approach doesn’t work. Any help would be super appreciated!

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 16

Commits related to this issue

Most upvoted comments

I am in the same boat…can’t seem to get anything to work when the scrolling element is anything other than the window.

am i missing something? i can’t find any working example for how to use this with an element ref.

Is it me, or does this hook not work at all for target elements that aren’t the window? It doesn’t fire at all unless the main document element is scrolling, regardless of the ref passed in.

Did anyone get this to work? I’m passing ref from a parent component and wont to detect scroll. But I get nothing when I do this:

useScrollPosition(({ prevPos, currPos }) => {
     console.log("scrolling");
}, [visibleFilterResultButton], props.forwardedRef);

Is it me, or does this hook not work at all for target elements that aren’t the window? It doesn’t fire at all unless the main document element is scrolling, regardless of the ref passed in.

Yep, this is due to getBoundingClientRect(). I think scrollTop should be used instead.