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 scroll page to the top after transition

I want my application to go to the top of the page when another page within the site is clicked. I have used the code from: https://v5.reactrouter.com/web/guides/scroll-restoration and put in a separate file.

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;
}

What I have tried:

I have placed <ScrollToTop /> before <Switch /> and after <BrowserRouter />as in the docs (these are in separate files).

Unlike the docs, the <App /> in my application is in a separate file, so <ScrollToTop /> is not placed near it.

When I console.log, I see it being hit at the correct instance (when there is a page change), but nothing occurs. I have also looked into many stackoverflow posts concerning the same issue, but I could not incorporate their suggestions.

What are possible issues:

Calling window.scrollTo(0, 0) outside the function does not seem to work. Are there any alternatives to this function?

Is the placement of <ScrollToTop /> incorrect? Does it have to be called near the <App />?

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

0

Welcome to Stackoverflow @user19251203

You have already gone half the way. You really don't need to create a component for it. You can create a custom hook and place it in your <App /> and then call it:

function App() {

  // Scroll to top on every transition custom hook
  const useScrollToTop = () => {
    const { pathname } = useLocation();

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

  useScrollToTop();

  return (
    <div className="App">
      .......
    </div>
  )
}

This way whenever you go to a new page, it scrolls to the top of the page.

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