0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【React】遷移後のページを最上部から表示する

Posted at

はじめに

React Routerでページ遷移を行う際、前画面でスクロールした状態が残ってしまいます。
遷移後のページを最上部から表示させるために、window.scrollTo(0, 0)を利用します。

実装

useLocationuseEffectを利用し、パス名が変わったときにwindow.scrollTo(0, 0)が実行されるようにします。

const ScrollToTop = () => {
  const { pathname } = useLocation()

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

  return null
}

作成したScrollToTopRouterでラップします。
これでComponentOne ComponentTwo ComponentThreeのどこに遷移しても、ページ最上部から表示されるようになります。

    <Router>
      <ScrollToTop />
      <Switch>
        <Route path={'/one'}>
          <ComponentOne />
        </Route>
        <Route path={'/two'}>
          <ComponentTwo />
        </Route>
        <Route path={'/three'}>
          <ComponentThree />
        </Route>
    </Router>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?