Skip to content

Instantly share code, notes, and snippets.

@fishactual
Last active August 8, 2022 03:56
Show Gist options
  • Save fishactual/2fff55f2cbf92871443135e469a9ac15 to your computer and use it in GitHub Desktop.
Save fishactual/2fff55f2cbf92871443135e469a9ac15 to your computer and use it in GitHub Desktop.
// 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