Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!