I noticed that when ever I access a route, the page scrolls automatically to the bottom when I use <Link>, I am a bit confused because it is working and I get the page but it scrolls automatically all the way to the bottom by this behavior.
Here is the router:
import {Link,Routes,Route,Navigate} from 'react-router'
const App = () => {
const user=true
return <div>
<Routes>
<Route exact path='/' element={<Home/>} />
<Route exact path="/products/:category" element={ <ShoppingCat/>}/>
<Route exact path="/product/:id" element={ <ProductView/>}/>
<Route exact path="/cart" element={ <Cart/>}/>
<Route exact path="/login" element={user?<Navigate to='/'/>: <Login/>}/>
<Route exact path="/register" element={ user? <Navigate to='/'/> :<Register/>}/>
</Routes>
this is a button to access the <ProductView/> route:
<Link to={`/product/${product._id}`}>
<button className='btn-4'>View </button>
</Link>
Without seeing anymore code my guess would be that your button location is actually at the bottom of the page so when you change route you are staying at the bottom as you have no scroll to top component.
To scroll to the top on every route change do the following.
New component ScrollToTop.js
import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return (null);
}
export default withRouter(ScrollToTop);
Then change your app.js to this
import {Link,Routes,Route,Navigate} from 'react-router'
const App = () => {
const user=true
return <div>
<ScrollToTop />
<Routes>
<Route exact path='/' element={<Home/>} />
<Route exact path="/products/:category" element={ <ShoppingCat/>}/>
<Route exact path="/product/:id" element={ <ProductView/>}/>
<Route exact path="/cart" element={ <Cart/>}/>
<Route exact path="/login" element={user?<Navigate to='/'/>: <Login/>}/>
<Route exact path="/register" element={ user? <Navigate to='/'/> :<Register/>}/>
</Routes>
</div>
While the answer above is good for older versions, withRouter and history no longer exist in V6 so here is how the scroll to the top wrapper looks in later version :
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
and in index.js :
import ScrollToTop from "./ScrollToTop";
ReactDOM.render(
<Router>
<ScrollToTop />
<App />
</Router>,
document.getElementById("root")
);