_app.tsx
const router = useRouter()
useEffect(() => {
window.history.scrollRestoration = 'auto'
const cacheScrollPositions: Array<[number, number]> = []
let shouldScrollRestore : null | {x: number; y: number}
router.events.on('routeChangeStart', () => {
cacheScrollPositions.push([window.scrollX, window.scrollY])
})
router.events.on('routeChangeComplete', () => {
if (shouldScrollRestore) {
const {x, y} = shouldScrollRestore
window.scrollTo(x, y)
shouldScrollRestore = null
}
window.history.scrollRestoration = 'auto'
})
router.beforePopState(() => {
if (cacheScrollPositions.length > 0) {
const scrollPosition = cacheScrollPositions.pop()
if (scrollPosition) {
shouldScrollRestore = {
x: scrollPosition[0],
y: scrollPosition[1]
}
}
}
window.history.scrollRestoration = 'manual'
return true
})
}, [router])
์๋ฆฌ
1. router ์ด๋ ์์ ์ cacheScrollPosition ์ ํ์ฌ window ์ scroll x,y ์์น ๊ฐ ์ ์ฅ
2. pop ๋๊ธฐ ์ ์ ๊ฐ์ฅ ์์ ์๋ ๊ฐ์ ๊ฐ์ ธ์์ shouldScrollRestore ์ ์ ์ฅ ํ
3. router ์ด๋์ด ์๋ฃ๋๋ฉด ํด๋น ๊ฐ์ผ๋ก ์คํฌ๋กค ํ๋ ๋ก์ง
์ฐธ๊ณ
'๐ Front-End > Next.js' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Dynamic Routes (0) | 2022.10.26 |
---|---|
Next.js - Assets, Meta data, CSS (0) | 2022.10.26 |
Next.js - Link (0) | 2022.10.26 |
Next.js - Routing (0) | 2022.10.26 |
Next.js - Pre Rendering (0) | 2022.10.26 |