Open History to see the last commit
1import {
2 defaultGetScrollRestorationKey,
3 restoreScroll,
4 storageKey,
5} from '@tanstack/router-core'
6import { useRouter } from './useRouter'
7import { ScriptOnce } from './ScriptOnce'
8β
9export function ScrollRestoration() {
10 const router = useRouter()
11 if (!router.isScrollRestoring || !router.isServer) {
12 return null
13 }
14 if (typeof router.options.scrollRestoration === 'function') {
15 const shouldRestore = router.options.scrollRestoration({
16 location: router.latestLocation,
17 })
18 if (!shouldRestore) {
19 return null
20 }
21 }
22 const getKey =
23 router.options.getScrollRestorationKey || defaultGetScrollRestorationKey
24 const userKey = getKey(router.latestLocation)
25 const resolvedKey =
26 userKey !== defaultGetScrollRestorationKey(router.latestLocation)
27 ? userKey
28 : undefined
29β
30 const restoreScrollOptions: Parameters<typeof restoreScroll>[0] = {
31 storageKey,
32 shouldScrollRestoration: true,
33 }
34 if (resolvedKey) {
35 restoreScrollOptions.key = resolvedKey
36 }
37β
38 return (
39 <ScriptOnce
40 children={`(${restoreScroll.toString()})(${JSON.stringify(restoreScrollOptions)})`}
41 />
42 )
43}