• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

141
Views
react router scroll to top when navigating to current page

I am using the following ScrollToTop component to scroll to the top of the page after navigating to a new page with react-router (copied from somewhere here at SO). This works as intended.

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

export default function ScrollToTop() {
    const { pathname } = useLocation();

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

    return null;
}

<ScrollToTop /> is located within my App.js right below my react-helmet and above my <Header /> component.

However, when navigating to the current page (e.g. I open website/about, scroll down and navigate to website/about again), then I stay at the current position without scrolling back to the top. I am assuming this is the case because the component doesn't get reloaded?

What I would expect/like to happen is that the page scrolls to the top on every navigation, even when navigating to the current page.

How can I achieve this?

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Allright - after looking around and fiddling some more, I stumbled upon this right here: stackoverflow: react-router scroll to top on every transition

I discarded this at first because I assumed it would do pretty much the same thing as my code. Boy was I wrong. This code does exactly what I was looking for.

Only one thing: I was getting an error about a missing dependency:

React Hook useEffect has a missing dependency: 'history'.

Adding history to the dependencies fixed this issue. Here the final code, mostly copied from the post linked above:

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

function ScrollToTop({ history }) {
    useEffect(() => {
        const unlisten = history.listen(() => {
            window.scrollTo(0, 0);
        });
        return () => {
            unlisten();
        };
    }, [history]);

    return null;
}

export default withRouter(ScrollToTop);
almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error