React-Router Scroll to Top on Every Transition

React Router scroll page to the top after transition

Can you try the below

 <BrowserRouter >        
<Layout>
<ScrollToTop />
<Switch>
<Route path="/" exact component={MainPageConfig} />
</Switch>
</Layout>
</BrowserRouter>

react router scroll to top when navigating to current page

Allright - after looking around and fiddling some more, I stumbled upon this right here: stackoverflow: react-router scroll to top on every transition

I discarded this at first because I assumed it would do pretty much the same thing as my code. Boy was I wrong. This code does exactly what I was looking for.

Only one thing: I was getting an error about a missing dependency:

React Hook useEffect has a missing dependency: 'history'.

Adding history to the dependencies fixed this issue. Here the final code, mostly copied from the post linked above:

import { useEffect } from "react";
import { withRouter } from "react-router-dom";

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

return null;
}

export default withRouter(ScrollToTop);

React Router Scroll to Top on V6

As others have pointed out, you are wrapping your Routes component with the ScrollToTop component, but instead of editing it to render its implicit children prop I suggest converting it to a React hook, especially considering since it doesn't actually render anything, you want it to run as a side-effect of navigation.

function useScrollToTop() {
const { pathname } = useLocation();

useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
}

...

function App() {
useScrollToTop();
return (
<div className="App">
<div className="app-body">
<NavBar />
<Routes>
<Route path="/portfolio" element={<Main />} />
<Route path="/portfolio/projects" element={<Projects />} />
</Routes>
</div>
</div>
);
}

This necessarily requires you to lift the Router higher in the ReactTree to wrap the App component so it has a routing context to use for the useScrollToTop hook.

const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<Router>
<App />
</Router>
</StrictMode>,
rootElement
);


Related Topics



Leave a reply



Submit