Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
ScrollToTop implementation with v6 of react router dom

I have an issue when navigating into another page, its position will remain like the page before. So it won't scroll to top automatically. I am currently using "react-router-dom": "^6.2.1",

ScrollToTop.js

import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom'; 

const withRouter = (Component) => {
  const Wrapper = (props) => {
    let history = useNavigate();
    return (
      <Component
        history={history}
        {...props}
        />
    );
  };
  
  return Wrapper;
};

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

  return (null);
}

export default withRouter(ScrollToTop);

App.js I am returning following fragment

return (
    <>
    <Router>
      <Header/>
      <ScrollToTop />
      {isAuthenticated && <UserOptions user={user}/>}
      <Routes>
        <Route exact path="/" element={<Home /> }/>
        <Route exact path="/product/:id" element={<ProductDetails/>}/>
        <Route exact path="/products" element={<Products/>}/>
        <Route path="/products/:keyword" element={<Products/>}/>
        <Route exact path="/search" element={<Search/>}/>
        <Route exact path="/login" element={<LoginSignUp/>}/>
      </Routes>
      <Footer/>

    </Router>
    </>
  );
}
export default App;

After Adding ScrollToTop component I am not getting anything rendering in page. and It's showing error on console that "Uncaught TypeError: history.listen is not a function".

I am Beginner in MERN stack development so please guide me where I am wrong and what needed to change in my codebase.

I have taken reference from bellows Links

Stack Overflow: Scroll To Top.

GitHub: withRouter deprecated in V6?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda