Scroll to the top of the Page in React.js

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Photo from Unsplash

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> ); }

The examples in the code snippet show how to:

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

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

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.

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.

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.