#Implementing Tabs
1 messages · Page 1 of 1 (latest)
To implement tabs in Next.js while efficiently handling common data and routing, you can use a combination of parallel routes and layouts. This approach allows you to load common data once and switch between tabs without reloading the entire page. Here's how you can implement this:
- Create a layout for your library page that loads the common data:
// app/library/layout.tsx
import { Suspense } from 'react';
import Link from 'next/link';
async function fetchCommonData() {
// Fetch your common data here
}
export default async function LibraryLayout({
children,
posts,
drafts,
}: {
children: React.ReactNode;
posts: React.ReactNode;
drafts: React.ReactNode;
}) {
const commonData = await fetchCommonData();
return (
<div>
<h1>Library</h1>
<nav>
<Link href="/library">Posts</Link>
<Link href="/library/drafts">Drafts</Link>
</nav>
<Suspense fallback={<div>Loading...</div>}>
{children}
</Suspense>
</div>
);
}
- Create parallel routes for your tabs:
// app/library/page.tsx (Posts tab - default)
export default function PostsPage() {
return <div>Posts content</div>;
}
// app/library/drafts/page.tsx (Drafts tab)
export default function DraftsPage() {
return <div>Drafts content</div>;
}
// app/library/@posts/page.tsx (Posts parallel route)
export default function PostsParallel() {
return <div>Posts content</div>;
}
// app/library/@drafts/page.tsx (Drafts parallel route)
export default function DraftsParallel() {
return <div>Drafts content</div>;
}
This setup uses parallel routes, which allows you to render multiple pages in the same layout simultaneously. The common data is fetched once in the layout, and the tab content is loaded independently.
By using this approach, you can achieve the following:
- The common data is loaded once in the layout and doesn't reload when switching tabs.
- Tab switching is handled client-side, providing a smooth user experience.
- Each tab can have its own route (
/libraryfor posts and/library/draftsfor drafts).
This solution is based on the concepts of layouts and parallel routes in Next.js, as described in the Next.js documentation on parallel routes (https://nextjs.org/docs/app/building-your-application/routing/parallel-routes#examples) and layouts (https://nextjs.org/docs/app/building-your-application/routing/layouts-and-templates#layouts).
Remember that layouts in Next.js are Server Components by default (https://nextjs.org/docs/app/building-your-application/routing/layouts-and-templates#nesting-layouts), which allows for efficient data fetching and rendering.
By implementing tabs this way, you should be able to avoid the 5-second delay you were experiencing with dynamic routes, while still maintaining separate URLs for each tab and efficiently sharing common data.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@left vale Kapa.ai is still learning and improving, please let me know how I did by reacting below.