Saturday, December 28, 2024
Google search engine
HomeLanguagesHow to make your page scroll to the top when route changes?

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

Suppose we click on the About Us button, we are directed to a different page, but it doesn’t load from the top. We have to scroll up ourselves to see the content from the beginning. Our new page loads from the height at which our About Us button (of the previous page) was.

This happens because react-router-dom only knows to change the route. It cannot load the page from a different position. So, we have to make a different functional component for loading our page from the top when we change the route.

Prerequisite:

  • Basic knowledge of npm & create-react-app command.
  • Basic knowledge of styled-components.
  • Basic knowledge of useEffect React hooks.
  • Basic knowledge of react-router-dom.

Basic Setup: You will start a new project using create-react-app command as shown below.

npx create-react-app react-router-scroll

Now go to your react-router-scroll folder by typing the given command in the terminal.

cd react-router-scroll

Required module: 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

Now create the components folder in src folder then go to the components folder and create four files Home.js, About.js, Styling.js, GoToTop.js.

Project Structure: The file structure in the project will look like this.

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.

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


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


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;
`; 


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


Explanation: 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.

App.js




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;


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/, you will see the following output. We can observe that the new route page is loading from the top as shown below.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments