Software Engineer at Supabase
May 3, 2024
When I use the `<Tab>` component from shadcn UI many times I want to sync that state of the tab with the URL so that users can deeplink to the tab or use the browser back/forth functions.
I made a simple hook that I call when I want to achieve this, looks like this:
import { useRouter } from "next/router";
export function useRouterTabs(name = "tab") {
const router = useRouter();
return {
tabValue: router.query.tab as string,
onTabChange: (tab: string) => {
router.push({
query: {
...router.query,
[name]: tab,
},
});
},
};
}
And in use it looks like this:
const { tabValue, onTabChange } = useRouterTabs("tab");
<Tabs
value={tabValue}
onValueChange={(tabVal) => {
onTabChange(tabVal);
}}
>
...
</Tabs>
And it works: