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.