Search code examples
reactjsscrollpositionscrollbar

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

  • Your main component has to have a ref. https://reactjs.org/docs/refs-and-the-dom.html Also you will use an event called onScroll in your component to update it. Check this out

    class ScrollAwareDiv extends React.Component {
      constructor(props) {
        super(props)
        this.myRef = React.createRef()
        this.state = {scrollTop: 0}
      }
    
      onScroll = () => {
        const scrollY = window.scrollY //Don't get confused by what's scrolling - It's not the window
        const scrollTop = this.myRef.current.scrollTop
        console.log(`onScroll, window.scrollY: ${scrollY} myRef.scrollTop: ${scrollTop}`)
        this.setState({
          scrollTop: scrollTop
        })
      }
    
      render() {
        const {
          scrollTop
        } = this.state
        return (
          <div
            ref={this.myRef}
            onScroll={this.onScroll}
            style={{
              border: '1px solid black',
              width: '600px',
              height: '100px',
              overflow: 'scroll',
            }} >
            <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
            <p>ScrollTop is {scrollTop}</p>
            <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
            <p>ScrollTop is {scrollTop}</p>
            <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
            <p>ScrollTop is {scrollTop}</p>
            <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
            <p>ScrollTop is {scrollTop}</p>
            <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
            <p>ScrollTop is {scrollTop}</p>
            <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
            <p>ScrollTop is {scrollTop}</p>
          </div>
        )
      }
    }
    
    ReactDOM.render(
      <ScrollAwareDiv />,
      document.getElementById('root')
    );
    

    https://codepen.io/JohnReynolds57/pen/NLNOyO