J. Hesters
J. Hesters

Reputation: 14796

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.

Upvotes: 7

Views: 37354

Answers (3)

Mohsin Ali Soomro
Mohsin Ali Soomro

Reputation: 11

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

Upvotes: 1

Midnight Blur
Midnight Blur

Reputation: 131

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);
}

Upvotes: 12

Gaspar Teixeira
Gaspar Teixeira

Reputation: 1267

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

Upvotes: 7

Related Questions