tabs with nextjs app router
Unanswered
Gg posted this in #help-forum
GgOP
hello, im trying to implement tabs where the tab contents are determined by the current route
This navigation is then imported in the layout of this pararell rotue group, so:
/users
/@tabs
/overview
page.tsx
/search
page.tsx
layout.tsx
navigation.tsx
it does do the job, and it keeps the animation on the tabs (im using park-ui)
however, I feel that the useState is unnecessary since the pathname should be keeping its own state. but when I remove the useState and just use the segment, the animation on the tabs disappear and it becomes janky (taking long to switch between tabs sometimes). And when I log the pathname, it gets logged like 50 times when not using the useState. What could be the reason for this?
"use client";
import { useRouter, useSelectedLayoutSegment } from "next/navigation";
import { useState } from "react";
import * as Tabs from "@/components/ui/tabs";
const usersPages: UsersPage[] = [
{
href: "overview",
label: "Overview",
segment: "overview",
},
...
];
export const Navigation = ({ children }: { children: React.ReactNode }) => {
const pathname = usePathname();
const router = useRouter();
const [activeTab, setActiveTab] = useState(pathname);
console.log("pathname", pathname);
const handleTabChange = (value: string) => {
setActiveTab(value);
router.push(value);
};
return (
<Tabs.Root
value={activeTab}
onValueChange={({ value }) => {
handleTabChange(value);
}}
>
<Tabs.List>
{usersPages.map(usersPage => (
<Tabs.Trigger key={usersPage.href} value={usersPage.href}>
{usersPage.label}
</Tabs.Trigger>
))}
<Tabs.Indicator />
</Tabs.List>
<Tabs.Content value={activeTab}>{children}</Tabs.Content>
</Tabs.Root>This navigation is then imported in the layout of this pararell rotue group, so:
/users
/@tabs
/overview
page.tsx
/search
page.tsx
layout.tsx
navigation.tsx
it does do the job, and it keeps the animation on the tabs (im using park-ui)
however, I feel that the useState is unnecessary since the pathname should be keeping its own state. but when I remove the useState and just use the segment, the animation on the tabs disappear and it becomes janky (taking long to switch between tabs sometimes). And when I log the pathname, it gets logged like 50 times when not using the useState. What could be the reason for this?