coding/javascript
페이지 전환 시 스크롤 위치 기억 하기 구현
코딩희송
2021. 12. 22. 15:26
개발스펙
- React
- Typescript
- Zustand
로직
1. currentTarget
을 이용해 클릭한 좌표 구하기
2. state에 좌표 저장
- list.tsx
// 페이지 이동 함수
const handleMovePage = (e:React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
const { currentTarget } = e;
if (currentTarget) {
setScrollChk(currentTarget.parentElement?.scrollTop); // 스크롤 좌표 구해서 state 저장
// page 이동 로직
}
}
// 마운트 시 함수 연결
React.useEffect(()=>{
const scrollContainer = document.getElementById('scroll-container');
// 스크롤 엘리먼트와 좌표 state값이 존재하면 좌표값 할당
if (scrollContainer && scrollChk) scrollContainer.children[0].scrollTo({top: scrollChk});
}, [def]);
...
<button onClick={handleMovePage}> 페이지 이동 </button>
- useStore.ts
const useStore = () => {
...
scrollChk: undefined,
setScrollChk: scrollChk => set({ scrollChk })
...
}