Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

222
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda