How to scroll to top of the page in React

Last updated on Nov 22, 2020 by Suraj Sharma



In this tutorial, you will learn how you can scroll to the top of the page in React.


The JavaScript way to scroll to the top of the page is by using the scrollTo() method


Example:


window.scrollTo(0,0);


I am going to discuss two scenarios, where you might require to scroll to the top of the page.



1. Scroll to the top when you navigate to a different route


When you navigate to a different route, you require the page to automatically scroll to the top


To do this, call window.scrollTo(0,0) inside the useEffect() hook, with the empty dependencies array.


import React from 'react';

const ProductPage = () => {

  React.useEffect(()=>{
    window.scrollTo(0,0);
  }, []);

  return (
    <p>Product page</p>
  );
}

export default ProductPage;


2. Scroll to the top on a button click


If your app supports infinite loading then you will definitely require a button that scroll to the top on click of it


To achieve this, you can define a click event handler handleClick()



const BlogPost = () => {
  const handleClick = () => {
    window.scrollTo(0,0);
  }

  return (
    <button onClick={handleClick}>Top</button>
  );
}

export default BlogPost;


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.