Tracking scroll position of a component in React

17,838

Solution 1

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

Solution 2

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);
}
Share:
17,838

Related videos on Youtube

J. Hesters
Author by

J. Hesters

Ask better questions.

Updated on June 04, 2022

Comments

  • J. Hesters
    J. Hesters almost 2 years

    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.

  • justkeithcarr
    justkeithcarr over 3 years
    I was wondering if I used the onScroll event in a functional component instead of a class component, would I have to type " <div onScroll={ (event) => {scrollEvent(event)} }> " for the event to occur. For some reason it's not showing up in the console while I'm scrolling.
  • Midnight Blur
    Midnight Blur over 3 years
    It's working in a functional component too, maybe you have another issue? I've created a pen to demonstrate: https://codepen.io/midnightblurz/pen/NWrqaVw