-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
persist scroll positions in sessionStorage
- Loading branch information
1 parent
ef04b9c
commit dbf0416
Showing
2 changed files
with
21 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,31 @@ | ||
import { useEffect, useRef } from 'react' | ||
import { useEffect } from 'react' | ||
import { useLocation, useNavigation } from 'react-router-dom' | ||
|
||
function getScrollPosition(key: string) { | ||
const pos = window.sessionStorage.getItem(key) | ||
return pos && /^[0-9]+$/ ? parseInt(pos, 10) : 0 | ||
} | ||
|
||
function setScrollPosition(key: string, pos: number) { | ||
window.sessionStorage.setItem(key, pos.toString()) | ||
} | ||
|
||
/** | ||
* Given a ref to a scrolling container element, keep track of its scroll | ||
* position before navigation and restore it on return (e.g., back/forward nav). | ||
* Note that `location.key` is used as the cache key, not `location.pathname`, | ||
* Note that `location.key` is used in the cache key, not `location.pathname`, | ||
* so the same path navigated to at different points in the history stack will | ||
* not share the same scroll position. | ||
*/ | ||
export function useScrollRestoration(container: React.RefObject<HTMLElement>) { | ||
const cache = useRef(new Map<string, number>()) | ||
const { key } = useLocation() | ||
const key = `scroll-position-${useLocation().key}` | ||
const { state } = useNavigation() | ||
useEffect(() => { | ||
if (state === 'loading') { | ||
cache.current.set(key, container.current?.scrollTop ?? 0) | ||
} else if (state === 'idle' && cache.current.has(key)) { | ||
container.current?.scrollTo(0, cache.current.get(key)!) | ||
const pos = container.current?.scrollTop ?? 0 | ||
setScrollPosition(key, pos) | ||
} else if (state === 'idle') { | ||
container.current?.scrollTo(0, getScrollPosition(key)) | ||
} | ||
}, [key, state, container]) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters