Scroll to Top on Route Change Not Working

I’m working on a React project where I need the page to scroll to the top when navigating to a new route. I have implemented a ScrollToTop component, but it does not seem to work. The page retains its scroll position after navigation.

Despite implementing the ScrollToTop component and verifying that the console log outputs the correct pathnames, the page does not scroll to the top on route change. The previous scroll position is retained.

Troubleshooting Steps

  • Verified that the console.log statement in ScrollToTop.js works and logs the correct pathnames.
  • Ensured that ScrollToTop is included in App.js and wraps the Routes.

Additional Info

The code can be found on my GitHub Repository

I implemented a ScrollToTop component that uses the useEffect hook to scroll to the top of the page when the pathname changes. I expected this component to reset the scroll position to the top of the page whenever the route changes.

However, despite the component being correctly placed and logging the pathname changes, the page still retains its previous scroll position after navigation, which is not the intended behavior.

I also wanna say that I have read every relevant post on the matter on Stack Overflow and nothing seems to work for me. I have tried every resource to try and solve this issue.

App.js:

import React, { useState, useRef } from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import NavBar from "./components/NavBar.js";
import Contact from "./components/Contact.js";
import Widgets from "./components/widgets/Widgets.js";
import Footer from "./components/Footer.js";
import Currency from "./components/widgets/Currency.js";
import Timer from "./components/widgets/Timer.js";
import Weather from "./components/widgets/Weather.js";
import MainPage from "./components/MainPage.js";
import ScrollToTop from "./components/ScrollToTop.js";

function App() {
  const [isSidebarVisible, setIsSidebarVisible] = useState(true);

  const toggleSidebar = () => setIsSidebarVisible(!isSidebarVisible);

  const personalRef = useRef(null);
  const skillsRef = useRef(null);
  const workRef = useRef(null);
  const educationRef = useRef(null);
  const publicationsRef = useRef(null);

  const refs = {
    personal: personalRef,
    skills: skillsRef,
    work: workRef,
    education: educationRef,
    publications: publicationsRef,
  };

  return (
    <Router>
      <ScrollToTop />
      <div className="flex min-h-screen overflow-hidden">
        <NavBar 
          isSidebarVisible={isSidebarVisible} 
          toggleSidebar={toggleSidebar} 
          refs={refs}
        />
        <div
          className={`flex-1 flex flex-col transition-all duration-300 ${
            isSidebarVisible ? "ml-20" : "ml-0"
          }`}
        >
          <header className="flex justify-between items-center p-8 bg-gray-800 text-white fixed w-full top-0 left-0 z-30 transition-all duration-300">
            <h1
              className={`text-2xl transition-all duration-300 ${
                isSidebarVisible ? "ml-20" : "ml-0"
              }`}
            >
              Richard Lechko - IT Student @ DePaul University
            </h1>
            <button
              onClick={toggleSidebar}
              className="p-2 bg-blue-500 text-white rounded"
            >
              {isSidebarVisible ? "Close Sidebar" : "Open Sidebar"}
            </button>
          </header>
          <main className="flex-1 flex flex-col pt-24 overflow-hidden">
            <Routes>
              <Route
                path="/"
                element={
                  <MainPage
                    personalRef={personalRef}
                    skillsRef={skillsRef}
                    workRef={workRef}
                    educationRef={educationRef}
                    publicationsRef={publicationsRef}
                  />
                }
              />
              <Route path="/contact" element={<Contact />} />
              <Route path="/widgets" element={<Widgets />} />
              <Route path="/widgets/currency" element={<Currency />} />
              <Route path="/widgets/timer" element={<Timer />} />
              <Route path="/widgets/weather" element={<Weather />} />
            </Routes>
            <Footer refs={refs} />
          </main>
        </div>
      </div>
    </Router>
  );
}

export default App;

ScrollToTop.js:

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

const ScrollToTop = () => {
  const { pathname } = useLocation();

  useEffect(() => {
    console.log('ScrollToTop: Pathname changed to', pathname);
    setTimeout(() => {
      window.scrollTo(0, 0);
    }, 0);
  }, [pathname]);

  return null;
};

export default ScrollToTop;

NavBar.js:

import React, { useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import {
  FaUser,
  FaTools,
  FaBriefcase,
  FaGraduationCap,
  FaBook,
  FaEnvelope,
} from "react-icons/fa";

const NavBar = ({ isSidebarVisible, refs, toggleSidebar }) => {
  const navigate = useNavigate();
  const location = useLocation();

  const handleNavClick = (sectionId) => {
    if (refs[sectionId] && refs[sectionId].current) {
      refs[sectionId].current.scrollIntoView({ behavior: "smooth" });
    } else {
      navigate("/");
      setTimeout(() => {
        if (refs[sectionId] && refs[sectionId].current) {
          refs[sectionId].current.scrollIntoView({ behavior: "smooth" });
        }
      }, 100);
    }
  };

  const handleExternalNavClick = (path) => {
    navigate(path, { replace: true });
  };

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

  return (
    <div
      className={`fixed top-0 h-screen ${
        isSidebarVisible ? "w-20" : "w-0"
      } bg-gray-900 text-white shadow-lg transition-all duration-300 z-40`}
    >
      <nav>
        <ul>
          <NavItem icon={<FaUser size={28} />} onClick={() => handleNavClick('personal')} />
          <NavItem icon={<FaTools size={28} />} onClick={() => handleNavClick('skills')} />
          <NavItem icon={<FaBriefcase size={28} />} onClick={() => handleNavClick('work')} />
          <NavItem icon={<FaGraduationCap size={28} />} onClick={() => handleNavClick('education')} />
          <NavItem icon={<FaBook size={28} />} onClick={() => handleNavClick('publications')} />
          <NavItem icon={<FaEnvelope size={28} />} onClick={() => handleExternalNavClick('/contact')} />
          <NavItem icon={<FaTools size={28} />} onClick={() => handleExternalNavClick('/widgets')} />
        </ul>
      </nav>
    </div>
  );
};

const NavItem = ({ icon, onClick }) => {
  return (
    <li onClick={onClick}>
      <div className="flex justify-center items-center p-4 hover:bg-gray-700 transition-colors cursor-pointer">
        {icon}
      </div>
    </li>
  );
};

export default NavBar;

New contributor

Richard Lechko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật