일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- vscode
- Algorithm
- java
- frontend
- 그레이들
- DFS
- 안드로이드
- Redux
- network
- TypeScript
- 자바
- react
- 다이나믹 프로그래밍
- 알고리즘
- DP
- VIM
- Data Structure
- BFS
- 동적 계획법
- CS
- git
- Graph
- Python
- db
- Javascript
- 리트코드
- Database
- 백준
- LeetCode
- 프로그래머스
- Today
- Total
늘 겸손하게
React - 페이지 전환시 스크롤 위치 초기화 본문
React로 웹 페이지를 개발하는 중에 다른 페이지로 전환이 되었을 때 스크롤의 위치가 맨 위로 초기화되어야 하지만 전환되기 이전 페이지와 비슷한 위치에 있는 문제가 발생하였습니다. 구글에 찾아보니 쉽게 해결책을 찾을 수 있었고 react-router 문서에도 해결책이 나와 있었습니다
영어로는 scroll-restoration이라고 부릅니다
https://v5.reactrouter.com/web/guides/scroll-restoration
Declarative routing for React apps at any scale | React Router
Version 6 of React Router is here! React Router v6 takes the best features from v3, v5, and its sister project, Reach Router, in our smallest and most powerful package yet.
reactrouter.com
아예 컴포넌트를 통째로 다운받는것도 가능합니다
https://www.npmjs.com/package/react-router-scroll-top
react-router-scroll-top
An easy scroll to top component based on the React Router Scroll Restoration Example. Latest version: 0.3.1, last published: 5 months ago. Start using react-router-scroll-top in your project by running `npm i react-router-scroll-top`. There are 5 other pro
www.npmjs.com
코드
1
2
3
4
5
6
7
8
9
10
11
12
|
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const {pathname} = useLocation();
useEffect(()=> {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
|
cs |
react의 useEffect를 이용하여 side effect를 줄 수 있습니다. useEffect는 react 생명주기의 componentDidMount와componentDidUpdate,componentWillUnmount가 합쳐진 것으로 생각해도 좋습니다.
주의할점은 위 ScrollToTop 컴포넌트를 Router 아래에 배치해야합니다.
1
2
3
4
5
6
7
8
9
10
11
|
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<div>
<Route exact path="/"><App/></Route>
<ScrollToTop/>
<Route path="/second"><Component/></Route>
</div>
</BrowserRouter>
);
|
cs |