I am trying to get the scroll position of a div in React. I tried getting the window the scroll values the values are always 0.
handleScrollPosition(e){
console.log("inside handle scroll")
console.log(window.scrollX, window.scrollY)
}
<SearchListWrapper className="TestSL" onScroll={this.handleScrollPosition} />
CodePudding user response:
If you want scroll position of the page, what you are doing should work, but remind you, that you won't get scroll until you scroll on entire page height.
If you want to get position of the element relative to the page you can you this method: getBoundingClientRect().top
. In JavaScript this is used with followingly:
document.getElementById(element).getBoundingClientRect().top;
But as you are in React you are not supposed to be refering to elements in this way. You should use useRef
that you give to the element that you want the position of and then use
yourRef.current.getBoundingClientRect().top
So example of this is:
export default function App() {
const divRef = React.useRef();
if (divRef) {
console.log(divRef.current.getBoundingClientRect().top);
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2> Start editing to see some magic happen!</h2>
<div ref={divRef}>Text</div>
</div>
);
}
Alternative to this solution to this is here: Get scroll position with Reactjs
CodePudding user response:
Solution
handleScrollPosition(e){
const scrollTop = document.getElementById("TestSL").scrollTop;
//use scrollTop here
}
<SearchListWrapper id="TestSL" onScroll={this.handleScrollPosition} >