LoginSignup
33
26

More than 5 years have passed since last update.

[React]react-router v4で画面遷移時に前のページのスクロール位置が残る

Last updated at Posted at 2018-04-01

概要

react-routerを使用したプロジェクトにおいて、画面遷移時に前のページのスクロール位置が残ってしまい、ページの最上部から表示されない問題を解決したのでメモとして残しておく。

解決法

普通にreact-routerの公式ドキュメントに解決法があった。

実装

コンポーネントを作る

ScrollToTop.jsx
import { Component } from 'react';
import { withRouter } from 'react-router-dom';

class ScrollToTop extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0);
    }
  }

  render() {
    return this.props.children;
  }
}

export default withRouter(ScrollToTop);

インポートする

react-routerを使用しているコンポーネントにインポートする

import ScrollToTop from './components/ScrollToTop';

ラップする

<ScrollToTop>でラップします。

<Router>
  <ScrollToTop>
    <App />
  </ScrollToTop>
</Router>
33
26
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
33
26