Reputation: 6472
In react, I am trying to make scrollToTop work.
Somehow, It doesn't work.
https://codesandbox.io/s/quiet-shape-5iov0?file=/src/App.js Here is the codesandbox. scroll down and there's should be button, called click
which scrolls up, but it doesn't work.
Upvotes: 0
Views: 69
Reputation: 9779
Try this if you just need to scroll top.
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth"
});
function
const nice = () => {
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth"
});
};
Another way using scrollIntoView()
const nice = () => {
document.querySelector("body").scrollIntoView({
behavior: "smooth"
});
};
For better understanding, checkout window.scrollTo
Upvotes: 3
Reputation: 26
If you dont want to use window
object
const nice = () => {
const root = document.querySelector("body");
console.log(root, " root");
root.scrollIntoView({
behavior: "smooth"
});
};
Upvotes: 0
Reputation: 3846
You can scroll to top by using the window object like this :
window.scrollTo(0,0)
Upvotes: 0
Reputation: 301
The scrollTo is a window function so just attach it there:)
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth"
});
Upvotes: 0