1

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?

Meet
  • 19
  • 2
  • The `useNavigate` hook returns a `navigate` ***function***, not a history object; there is no listener function to invoke on it. If you need access to the `history` object then you'll currently need to create a custom router that accepts a custom history object that can then be used to do any route change listening. See my answer [here](https://stackoverflow.com/a/70646548/8690857) for how to do this. – Drew Reese Jan 11 '22 at 19:15

0 Answers0