react: scroll to the top of page on transition

2021-09-09

 | 

~2 min read

 | 

225 words

I’m currently working on a single page app with React that uses React Router. When navigating between “pages” (that is the URL changed and the router loads a totally new component), it was a fairly common experience to end up “starting” in the middle of the page. The solution I ended up using is a “Scroll to top” approach.

Browsers are starting to implement this themselves, but an easy way to implement this with React is to look at the pathname of the URL and if it changes, use the Window’s scrollTo API.

ScrollToTop.tsx
import { useEffect } from "react"

export function ScrollToTop() {
  const pathname = window.location.pathname
  useEffect(() => {
    window.scrollTo(0, 0)
  }, [pathname])
  return null
}

The above is a generic ScrollToTop regardless of which router you’re using. However, if you’re using react-router, we can take advantage of the useLocation hook too:

ScrollToTop.tsx
import { useEffect } from "react"
import { useLocation } from "react-router"

export function ScrollToTop() {
  const { pathname } = useLocation()
  useEffect(() => {
    window.scrollTo(0, 0)
  }, [pathname])
  return null
}

This could then be used as the first element in the Router:

App.tsx
const App = () => {
  return (
    <Router>
      <ScrollToTop />
      <Switch>
        <Route>{/**/}</Route>
        // ...
      </Switch>
    </Router>
  )
}

This approach is what the React-Router docs suggest in their Scroll Restoration guide.


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!