
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;
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;
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)
For further actions, you may consider blocking this person and/orreporting abuse