Last active
August 8, 2022 03:56
-
-
Save fishactual/2fff55f2cbf92871443135e469a9ac15 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Hook | |
import { useRouter } from 'next/router'; | |
import { useState, useEffect } from 'react'; | |
export const useSyncRouterWithTabs = ({ | |
tabs, | |
defaultIndex, | |
}: { | |
tabs: string[]; | |
defaultIndex?: number; | |
}) => { | |
const router = useRouter(); | |
const [tabIndex, setTabIndex] = useState(defaultIndex ? defaultIndex : 0); | |
useEffect(() => { | |
if (!tabs.length) { | |
throw new Error('One or more tab is required'); | |
} | |
tabs.map((t, i) => { | |
if (router.query.t === t) { | |
setTabIndex(i); | |
} | |
}); | |
}, [router.query, tabs]); | |
const handleTabsChange = (index: number) => { | |
setTabIndex(index); | |
tabs.map((t, i) => { | |
if (i === index) { | |
router.query.t = t; | |
router.push( | |
{ | |
query: { ...router.query }, | |
}, | |
undefined, | |
{ shallow: true } | |
); | |
} | |
}); | |
}; | |
return [tabIndex, handleTabsChange] as const; | |
}; | |
// Usage | |
const [tabIndex, handleTabsChange] = useSyncRouterWithTabs({ | |
tabs: ['overview', 'candidates', 'events'], | |
defaultIndex: 1, | |
}); | |
return ( | |
<Tabs index={tabIndex} onChange={handleTabsChange}> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment