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

393
Visualizações
Scroll to top on every transition react-router-dom v6

I'm trying to scroll on top of each page change with react-router dom v6. The code is scrolling back on top only on my home page and not on my character details page. I've tried many solutions but can't get them to work. I'm using "react-router-dom": "^6.2.2",

This is what I have achieved so far:

ScrollToTop.js:

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

export default function ScrollToTop({ children }) {
    const { pathname } = useLocation();
    
    useEffect(() => {
        window.scrollTo(0, 0);
    }, [pathname]);
    
    return children;
}

My app.js

  <Router>
    <ScrollToTop>
      <Header />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/character/:char_id" element={<CharacterDetail />} />
        <Route path='*' element={<PageNotFound />} />
      </Routes>
      <Footer />
    </ScrollToTop>
  </Router>

I also tried doing my component directly using 'window.scrollTo(0, 0);' and by scrolling to an ID in my useEffect without success. Grateful for your guidance.

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

0

It seems it can also depend on the browser, some browsers are starting to handle "scroll restoration" by them self's (specs).

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

export default function ScrollToTop({ children }) {
  const { pathname } = useLocation();
  
  useEffect(() => {
    const canControlScrollRestoration = 'scrollRestoration' in window.history
    if (canControlScrollRestoration) {
      window.history.scrollRestoration = 'manual';
    }

    window.scrollTo(0, 0);
  }, [pathname]);
  
  return children;
}

Bonus note: I would not pass children to this component but rather render it as a sibling to App, this way it wouldn't trigger a re-render when location changes, unless necessary:

<Router>
  <ScrollToTop />
  <App />
</Router>
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