[React] 새 페이지 렌더링 시 상단에서 시작하기

1 minute read

리액트는 새 페이지를 렌더링한 후 스크롤을 맨 위로 올려주지 않는다. 그래서 별도로 컴포넌트를 만들어서 설정해주어야 한다.

먼저 ScrollToTop.js 컴포넌트를 만든다.

 1import React, { Component } from 'react';
 2import { withRouter } from 'react-router';
 3
 4class ScrollToTop extends Component {
 5  componentDidUpdate(prevProps) {
 6    if (this.props.location !== prevProps.location) {
 7      window.scrollTo(0, 0)
 8    }
 9  }
10
11  render() {
12    return this.props.children
13  }
14}
15
16export default withRouter(ScrollToTop)

App.js 파일에 ScrollToTop 컴포넌트를 끼워 넣는다. 나의 경우는 아래와 같이 했다.

 1import React from 'react';
 2import { Switch, Route, Router } from 'react-router-dom';
 3import { Home, RefundPage, ChatbotPage, NotFoundPage } from '../pages';
 4import ScrollToTop from './ScrollToTop';
 5const App = () => {
 6    return (
 7        <div>
 8          <ScrollToTop>  // ScrollToTop으로 각 페이지를 감쌓다.
 9            <Switch>
10                <Route exact path="/" component={Home}/>
11                <Route path="/refund" component={RefundPage} />
12                <Route path="/refund/:Chatbot?" component={ChatbotPage} />
13                <Route component={NotFoundPage} />
14            </Switch>
15          </ScrollToTop>
16        </div>
17    );
18};
19
20export default App;