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