4

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.

fmsthird
  • 1,391
  • 2
  • 14
  • 31
  • 1
    Does `window.scrollTo` work if you call it directly in dev tools? This may have something to do with the HTML/CSS markup and which elements are scrollable. – Asher Lim Dec 30 '20 at 01:38
  • I tried to paste in the console but does not work either, it returns `undefined`, tried to use `document.getElementById("root").scrollTo(0, 0)` and still returns `undefined` – fmsthird Dec 30 '20 at 01:45
  • 3
    I see, I think `window.scrollTo(0,0)` returning undefined is expected behaviour. If the function `scrollTo` itself is undefined, that would be more problematic. If you're on Firefox and open up the dev tools you should be able to see which HTML elements are tagged with `scroll`. Then see if grabbing that `element.scrollTo(0,0)` works. – Asher Lim Dec 30 '20 at 01:52
  • thanks @AsherLim , fixed it by targeting the specific parent container. It was the way I implemented the page layout, the scrolling content is within the child container. – fmsthird Dec 30 '20 at 02:19

2 Answers2

2

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

calvinf
  • 3,645
  • 3
  • 26
  • 39
0

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); 
});
Josh
  • 727
  • 7
  • 16