Where do I have to put the window.scrollTo(0,0)
call in a react component?
I tried to put it directly into render
and also tried componentDidUpdate
(to wait till everything is rendered), but somehow the scrollbars always stay at the same position.
-- Edit --
The problem was CSS height/overflow of the window and body.
See: https://stackoverflow.com/a/18573599/1016383
scrollTo only works when the scroll behavior is set on html . If you have set overflow: scroll on some container inside of the DOM, then that need to be accessed. Assign an id to that. For example I have below div container for which I have set overflow: scroll .
Use the window. scrollTo() method to scroll to the top of the page in React, e.g. window. scrollTo(0, 0) . The scrollTo method on the window object scrolls to a particular set of coordinates in the document.
To scroll to an element on click in React:Set a ref prop on the element you want to scroll to. Set the onClick prop on the other element. Every time the element is clicked, call the scrollIntoView() method on the ref object.
Well, window.scrollTo(0,0) would always stick to the top of the page.
You are correct in saying this code should live in the componentDidMount function, but you need to tell it where to scroll. I would locate the id of the element you want to scroll to and obtain it's y coordinates, than you enter that into the window.scrollTo and it should work. You may need to get the height of the component and add that to this dymamic value you obtained.
window.scrollTo
only works when the scroll behavior is set on html
.
If scroll
is set on body
then document.querySelector("body").scrollTo(0,0)
If you have set overflow: scroll
on some container inside of the DOM, then that need to be accessed. Assign an id
to that. For example I have below div
container for which I have set overflow: scroll
.
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="root">
<div id="scroller">
<!-- other content -->
</div>
</div>
</body>
</html>
Then for scrolling behavior, you need to query the scroller
.
const scrollToTop = () => {
document.getElementById("scroller").scroll(0,0)
}
<button onClick={scrollToTop}>Scroll to Top</button>
This would work perfectly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With