-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathscrollable-tabs.ts
More file actions
33 lines (27 loc) · 949 Bytes
/
scrollable-tabs.ts
File metadata and controls
33 lines (27 loc) · 949 Bytes
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
31
32
33
import { useEffect, useRef } from "react"
import { TabInitialState, useTabState } from "reakit"
/** Retains scroll position for each tab */
export const useScrollableTabState = (initialState?: TabInitialState) => {
const tabs = useTabState(initialState)
const tabScrollPos = useRef<TabScrollPositions>({})
useEffect(() => {
// Restore the scroll position for the new tab.
const newScroll = tabScrollPos.current[tabs.selectedId!]
if (newScroll) {
window.scrollTo({ top: newScroll })
}
function listener() {
// Save scroll position for last tab.
const lastTabId = tabs.selectedId!
if (lastTabId) {
tabScrollPos.current[lastTabId] = window.scrollY
}
}
window.addEventListener("scroll", listener, { passive: true })
return () => window.removeEventListener("scroll", listener)
}, [tabs.selectedId])
return tabs
}
interface TabScrollPositions {
[x: string]: number
}