Last updated: Apr 7, 2024
Reading timeยท2 min
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.
import {useEffect} from 'react'; export default function App() { useEffect(() => { // ๐๏ธ Scroll to top on page load window.scrollTo({top: 0, left: 0, behavior: 'smooth'}); }, []); return ( <div> <h2>Top of the page</h2> <div style={{height: '155rem'}} /> {/* ๐๏ธ Scroll to top on button click */} <button onClick={() => { window.scrollTo({top: 0, left: 0, behavior: 'smooth'}); }} style={{ position: 'fixed', padding: '1rem 2rem', fontSize: '20px', bottom: '40px', right: '40px', backgroundColor: '#0C9', color: '#fff', textAlign: 'center', }} > Scroll to top </button> </div> ); }
The examples in the code sample show how to:
The window.scrollTo() method scrolls to a particular set of coordinates in the document.
<button onClick={() => { window.scrollTo({top: 0, left: 0, behavior: 'smooth'}); }} > Scroll to top </button>
The top
property on the object it takes specifies the number of pixels along
the Y
axis to scroll the window.
The left
property specifies the number of pixels to scroll the window on the
X
axis.
behavior
property specifies whether the scrolling should animate smoothly (smooth
), or happen instantly (auto
).The default value for the behavior
property is auto
.
You can use the useEffect hook if you need to scroll to the top of the page after the component renders.
useEffect(() => { // ๐๏ธ Scroll to top on page load window.scrollTo({top: 0, left: 0, behavior: 'smooth'}); }, []);
If you need to scroll to the top of the page when a button is clicked, set the
onClick
prop on the element, passing it a function.
The function should call the window.scrollTo()
method just like we did in the
useEffect
hook.
If you need to get the window's width and height, click on the following article.