Reactで遷移した後のページ位置がトップにならない

Category :

    react-routerのバージョンによって実装方法が異なるのですが、今回はv4の実装だけ記します。v3の実装方法は参考にリンクを載せておくのでそちらを参照ください。

    実装方針

    ページが変わるたびに位置をページの一番上にしたいので、URLのパスが変わったら処理をかけます。

    実装方法

    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);
    function App() {
    return (
    <Router>
    <ScrollToTop>
    <App />
    </ScrollToTop>
    </Router>
    );
    }

    解説

    ページが変わるたびに位置を上に戻したいのでcomponentDidUpdateを使用する。

    this.props.location.pathname !== prevProps.location.pathnameでパスが変更されたことを判定する。

    withRouterでルートコンポーネントをラップする。

    参考

    【React】遷移する度にページの一番上へスクロールさせる

    TOP
    © 2021 uichi