'Tracking scroll position of a component in React

I have a component that has a main tag in it with overflow: auto. Depending on the scroll height, I need to render a different element. How can I get an elements scroll position in React?

The basic gist is this:

function App() {
  return (
    <div>
      <main
        style={{
          backgroundColor: "red",
          overflow: "auto",
          height: "500px",
          padding: "5px"
        }}
      >
        Please Track Me!
        <div
          style={{ backgroundColor: "blue", color: "white", height: "5000px" }}
        >
          Inner
        </div>
      </main>
    </div>
  );
}

I need to track the main's (with overflow: auto) scroll position somehow.



Solution 1:[1]

It's actually pretty easy without using refs. The example bellow is in typescript.

element:

<div onScroll={this.scrollEvent}></div>

method:

 scrollEvent(e: SyntheticEvent) {
    const target = e.target as HTMLTextAreaElement;
    console.log('Current scroll position:', target.scrollTop);
}

Solution 2:[2]

You can track the component on scroll

export default function App() {
  const [scroll, setScroll] = useState(0);
  const onScroll = () => {
    const scrollY = window?.scrollY;
    const scrollTop = document.getElementById("test").scrollTop;

    setScroll(scrollTop);
  };
  return (
    <div className="App">
      <h1>Scroll Position {scroll}</h1>
      <div
        id="test"
        onScroll={onScroll}
        style={{
          backgroundColor: "white",
          zIndex: "100",
          height: "200px",
          overflowY: "scroll"
        }}
      >
        content...
      </div>
    </div>
  );
}

Code

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Midnight Blur
Solution 2 Mohsin Ali Soomro