Open In App

How to make your page scroll to the top when route changes?

Last Updated : 25 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Clicking the “About Us” button in a React application doesn’t automatically scroll to the top of the page load, as react-router-dom only changes the route without resetting the scroll position; a separate functional component is needed to ensure the new page loads from the top when the route changes.

Prerequisite:

Steps to Create React Application And Installing Module:

Step 1: Create a React application using the following command:

npx create-react-app react-router-scroll

Step 2: After creating your project folder i.e. folder name, move to it using the following command:

cd react-router-scroll

Step 3: Install the dependencies required in this project by typing the given command in the terminal.

npm install react-router-dom
npm install --save styled-components

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.17.0",
"react-scripts": "5.0.1",
"styled-components": "^6.1.1",
"web-vitals": "^2.1.4",
}

Approach to implement scroll to top:

We initialize a variable by the name routePath and store the value of the current URL in it which is returned with useLocation() hooks. 

  • Now a function onTop is created which loads the webpage from the top whenever it is called. We pass this function as the first parameter (as a callback function) and our variable routePath as the second parameter (as a dependency) to our useEffect hooks. It means that our function onTop will only execute if the dependency routePath has changed between rendering. 
  • When we click on the About Us button, the value of routePath gets changed (as we are going to a new URL) and the function onTop gets triggered which loads our page from the top.

Example: In this example, we will design a functional component that loads our router page from the top, for that we will need to manipulate the App.js file and other created components file.

Javascript




import {
    BrowserRouter as Router,
    Switch, Route
} from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
function App() {
    return (
        <Router>
            <Switch>
                <Route path="/"
                    exact
                    component={Home} />
                <Route path="/about"
                    component={About} />
            </Switch>
        </Router>
    );
}
 
export default App;


Javascript




//GoToTop.js
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
 
export default function GoToTop() {
    const routePath = useLocation();
    const onTop = () => {
        window.scrollTo(0, 0);
    }
    useEffect(() => {
        onTop()
    }, [routePath]);
 
    return null;
}


Javascript




//Styling.js
import { Link } from 'react-router-dom';
import styled from 'styled-components';
   
export const Header = styled.h1`
   margin: 0;
   padding: 0;
   text-align: center;
   color: green;
`;
 
export const Content = styled.div`
   overflowY: scroll;
   height: 700px;
`;
 
export const RouterLink = styled(Link)`
   cursor: pointer;
   transition: all 0.2s ease-in-out;
   text-decoration: none;
`;
 
export const Button = styled.button`
  padding: 20px;
  font-size: 20px;
  position: relative;
  left: 42%;
  margin: 20px;
  cursor: pointer;
`;


Javascript




//About.js
import React from 'react'
import GoToTop from './GoToTop';
import { Header, Button, Content, RouterLink } from "./Styling";
const About = () => {
    return (
        <div>
            <Header>GeeksForGeeks About Us</Header>
            <Content></Content>
            <RouterLink to='/'>
                <Button>Return to Homepage</Button>
            </RouterLink>
            <Content></Content>
            <GoToTop />
        </div>
    )
}
 
export default About


Javascript




//Home.js
import React from 'react'
import GoToTop from './GoToTop'
import { Header, Button, Content, RouterLink } from "./Styling";
const Home = () => {
    return (
        <div>
            <Header>GeeksForGeeks Homepage</Header>
            <Content></Content>
            <RouterLink to='/about'>
                <Button>About Us</Button>
            </RouterLink>
            <Content></Content>
            <GoToTop />
        </div>
    )
}
 
export default Home


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000



Similar Reads

How to scroll to top on every Route click in Angular5 ?
We can use Router and NavigationEnd from '@angular/router' and hence we can scroll to the top of the webpage for every route. Approach: First, we need to import the Router and NavigationEnd from '@angular/router' in both app.module.ts file and app.component.ts.Then we need to create an instance of those in the constructor function.After creating th
2 min read
Laravel | Route::resource vs Route::controller
In Laravel, the Route actions can be controlled by any of the following two methods, either by using Route::resource method or by using Route::controller method. But both of them have their differences. Route::resource: The Route::resource method is a RESTful Controller that generates all the basic routes required for an application and can be easi
2 min read
How to navigate to a parent route from a child route?
In angular, a root component that serves as the parent component of all the components and the rest of the other components can be called a Child Component to the root component. This structure is in a form of a tree where a component that is the parent of a child lies above the child component and this there is no direct link between them but in g
4 min read
How to make a Sidebar Sticky on Page Scroll using CSS ?
A Sticky Sidebar contains important links and navigation options fixed on the screen, making it easy for users to access them while scrolling down. This improves the user experience by saving them from scrolling back to the top of the page to find essential information. We have used two different ways to achieve this effect including, position: fix
4 min read
Hide scroll bar, but while still being able to scroll using CSS
To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below: -webkit- (Chrome, Safari, newer versions of Opera): .element::-webkit-scrollbar { width: 0 !important } -moz- (Firefox): .element { overflow: -mo
3 min read
Scroll to the top of the page using JavaScript/jQuery
Have you ever find yourself wishing you could skip all that scrolling to get back to the top of a webpage? Well, good news! With JavaScript or jQuery, you can do just that. This article will walk you through the process. This trick will streamline your browsing experience. Say goodbye to endless scrolling and hello to instant page-top access! A scr
3 min read
How to display warning before leaving the web page with unsaved changes using JavaScript ?
To display a warning before leaving a web page with unsaved changes, you can use the beforeunload event in JavaScript. Syntax:// Event listener for the 'beforeunload' eventwindow.addEventListener('beforeunload', function (e) { // Check if any of the input fields are filled if (fname !== '' || lname !== '' || subject !== '') { // Cancel the event an
3 min read
How to scroll the page up or down using anchor element in jQuery ?
The problem is to include a slide effect whenever we click a local anchor and we want to scroll up or down the page accordingly. Earlier we can do it natively by using CSS property. Syntax: a { scroll-behavior: smooth; } Now with the help of jQuery, we can do it by using the following two methods: jQuery.offset() method: This method allows us to re
2 min read
How to display scroll update when scrolling down the page using jQuery ?
In this article, we will learn to show scroll updates when scrolling down on a webpage. The scroll() event handler can be used to detect any scrolling in the page, but we only need to detect the scrolling down. The scroll down event can be handled using the scroll() and scrollTop() events. HTML DOM Window Scroll() Method: The scroll event is sent t
2 min read
How to scroll down to bottom of page in selenium using JavaScriptExecutor
Selenium is an open-source popular web-based automation tool. The major advantage of using selenium is, it supports all browsers like Google Chrome, Microsoft Edge, Mozilla Firefox, and Safari, works on all major OS and its scripts are written in various languages i.e Java, Python, JavaScript, C#, etc. In this article, we will be working with Java
3 min read