Sync active key with URL on browser navigation

This commit is contained in:
srgooglo 2025-06-30 20:36:17 +02:00
parent 0d94ecc46d
commit 218df1c284

View File

@ -1,10 +1,9 @@
import React from "react"
export default ({
defaultKey = "0",
queryKey = "key",
}) => {
const [activeKey, setActiveKey] = React.useState(new URLSearchParams(window.location.search).get(queryKey) ?? defaultKey)
export default ({ defaultKey = "0", queryKey = "key" }) => {
const [activeKey, setActiveKey] = React.useState(
new URLSearchParams(window.location.search).get(queryKey) ?? defaultKey,
)
const replaceQueryTypeToCurrentTab = (key) => {
if (!key) {
@ -20,8 +19,21 @@ export default ({
replaceQueryTypeToCurrentTab(key)
}
return [
activeKey,
changeActiveKey,
]
const onHistoryChange = () => {
const newActiveKey = new URLSearchParams(window.location.search).get(
queryKey,
)
setActiveKey(newActiveKey ?? defaultKey)
}
React.useEffect(() => {
window.addEventListener("popstate", onHistoryChange)
return () => {
window.removeEventListener("popstate", onHistoryChange)
}
}, [])
return [activeKey, changeActiveKey]
}