window.scrollTo() in react components?
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.
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.