Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Scroll to top on page change React
Stephen Akugbe
Stephen Akugbe

Posted on

     

Scroll to top on page change React

If you are using React Router Dom for navigation and routing in your React app then you will notice that if you have a long content page and then you navigate to another long content page, you will stay scrolled down. This doesn't tell of a good user experience and as such you'll want the new page to be displayed from the top.
This short piece would show you how to complete that would having to add the same piece of code to every component or pages rendered in your react app. To accomplish this, we will make use of theuseEffect hook and theuseLocation hooks to achieve this.

NB: This article assumes you are already familiar with React-Router and you have already installed it in your react application.

First, you'll create a new wrapper component that handles the scroll restoration when you open a new page. For my

// src/components/ScrollToTop.jsximport { useEffect } from "react";import { useLocation } from "react-router-dom";const ScrollToTop = (props) => {    const location = useLocation();    useEffect(() => {      window.scrollTo({top: 0, left: 0, behavior: 'smooth' });    }, [location]);    return <>        {props.children}    </>  };export default ScrollToTop;
Enter fullscreen modeExit fullscreen mode

Next, import this wrapper component in yourApp.js and add it as a wrapper component within your Router as shown below.

//App.jsimport {  BrowserRouter as Router,  Routes,  Route} from 'react-router-dom';const App = () => {  return (    <Router>      <ScrollToTop>        <Routes>          {* All your other imported components *}        </Routes>      </ScrollToTop>    </Router>  );};export default App;
Enter fullscreen modeExit fullscreen mode

Notice that theScrollToTop component wraps theRoutes component but stays inside theRouter component. This order is important and must be followed to achieve the desired result.

Thanks for reading and don't forget to drop a like if this article helped you.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Seasoned developer with 6+ years experience in crafting high-performance web applications and RESTful APIs. Proficient in Laravel and Node.js, Next.js and React
  • Location
    Paris, France
  • Education
    University of Benin, Nigeria
  • Pronouns
    He/Him
  • Work
    Software Engineer
  • Joined

More fromStephen Akugbe

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp