I am trying to fix the scrolling issue in React wherein when I was to scroll down to a certain point on the page, and then navigates to another page, that page will begin at the same scroll point as the previous page.
Here's what I tried:
import { useLocation } from 'react-router'
const ScrollToTop: React.FC = () => {
const { pathname } = useLocation()
React.useEffect(() => {
console.log('im scrolling')
window.scrollTo(0, 0)
}, [pathname])
return null
}
export default ScrollToTop
And then imports it like this:
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import ScrollToTop from './components/base/ScrollToTop'
import Apps from './App'
ReactDOM.render(
<BrowserRouter>
<ScrollToTop />
<Apps />
</BrowserRouter>,
document.getElementById('root'),
)
Im scrolling is printing in the console but the window.scrollTo is not working.
I also tried the useLayoutEffect, but the same result still not scrolling.
Try grabbing document.documentElement or another specific element instead of window.
const location = useLocation();
useLayoutEffect(() => {
document.documentElement.scrollTo(0, 0);
}, [location.pathname]);
Related: react-router scroll to top on every transition
I had this same issue with react-router v6 and using the following instead of window.scrollTo(0, 0) worked for me:
useEffect(() => {
document.body.scrollTo(0, 0);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With