Scroll to the top of the Page in React.js

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# Scroll to the top of the Page in React.js

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.

App.js
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> ); }

react srcoll to top of page

The code for this article is available on GitHub

The examples in the code sample show how to:

  1. Scroll to the top of the page after rendering the component.
  2. Scroll to the top of the page on a button click.

The window.scrollTo() method scrolls to a particular set of coordinates in the document.

App.js
<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.

The 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.

App.js
useEffect(() => { // ๐Ÿ‘‡๏ธ Scroll to top on page load window.scrollTo({top: 0, left: 0, behavior: 'smooth'}); }, []);
The code for this article is available on GitHub
We passed an empty dependencies array to the hook, so it's only going to run on the initial render.

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.

Want to learn more about handling scroll events in React? Check out these resources: Scroll to an element on click in React,Scroll to the bottom of a div in React,Handle the onScroll event in React.

If you need to get the window's width and height, click on the following article.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev