Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router v6 window.scrollTo does not work

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.

like image 908
fmsthird Avatar asked Jul 31 '26 03:07

fmsthird


2 Answers

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

like image 199
calvinf Avatar answered Aug 02 '26 18:08

calvinf


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); 
});
like image 30
Josh Avatar answered Aug 02 '26 17:08

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!