How to scroll to the top of a webpage in React
In this tutorial, we are going to learn about how to scroll to the top of a webpage in the React app.
To scroll the top of a webpage in React, call the window.scrollTo() method by passing the ‘top: 0’, ‘bottom: 0’ as a co-ordinates.
Here is an example, where it scrolls to the top of a page by the button click:
import React from "react";
export default function App() {
const handleClick = () => {
window.scollTo({top:0, left: 0, behaviour: 'smooth'});
};
return (
<div className="App" >
<h1>Top of the page</h1>
<div style={{ height: '120rem' }}>
<button onClick={handleClick} className="scrolltoTop">
ScrollToTop
</button>
</div>
</div>
);
}
In the above code, we have passed the options object to a window.scrollTo() method. So, that it moves the top of a page when a button is clicked.
The top property specifies the number of pixels it will scroll in vertical direction(y-axis) to the window or element.
The left property specifies the number of pixels it will scroll in horizontal direction(x-axis) to the window or element.
The ‘behavior:smooth’ property adds the smooth scrolling animation to the page.
Scrolling to the top of a page after component is rendered
To scroll to the of a page after a component is rendered in React, call the window.scrollTo() method inside the useEffect() hook.
Here is an example:
import React, {useEffect} from "react";
export default function App() {
useEffect(() => {
window.scollTo({top:0, left: 0, behaviour: 'smooth'});
}, []);
return (
<div className="App" >
<h1>Top of the page</h1>
<div style={{ height: '120rem' }}>
<button onClick={handleClick} className="scrolltoTop">
ScrollToTop
</button>
</div>
</div>
);
}
In the example above, we have passed two arguments to the useEffect hook, the first one is the function , the second one is the empty array []. So, that it runs the function on the intial render of a page.