Tabs Component in React: Underline, Pills, Scrollable, Vertical
Build every tabs variant you'll ever need in React - underline, pills, scrollable, and vertical - with accessible keyboard nav and zero extra dependencies.
Why Tabs Are Harder Than They Look
Tabs look trivial. You've seen a hundred implementations on Stack Overflow - a useState, a mapped list of buttons, conditional rendering. Done in 20 lines. Ship it. But then your designer asks for a scrollable tab bar on mobile, a vertical layout for the settings page, and a pill-style variant for the analytics dashboard. Suddenly your 20-line component is four diverging codebases that share almost nothing.
In practice, the real complexity in tabs isn't the visual layer - it's the accessibility requirements you probably skipped the first time. The ARIA tablist, tab, and tabpanel roles. Keyboard navigation: Arrow Left/Right to move focus, Home/End to jump to ends, Enter or Space to activate. Focus management when tabs are removed dynamically. These aren't optional if you're building anything that ships to real users.
This guide covers every major tabs variant you'll actually encounter in production, builds them on a single shared primitive, and keeps all four variants keyboard-accessible. No Radix, no Headless UI - just React 18 and Tailwind. That said, if you want production-ready components without the build time, Empire UI ships all of these with animations, dark mode, and accessibility built in.
The Shared Primitive: useTabs Hook
Before writing a single variant, pull the stateful logic into a hook. Every tabs variant needs the same thing: which tab is active, a setter for it, and a stable way to generate IDs for the ARIA attributes. Separating that from the rendering layer means you can swap visual styles without touching the logic.
// useTabs.ts
import { useState, useId } from 'react';
export interface TabItem {
id: string;
label: string;
content: React.ReactNode;
disabled?: boolean;
}
export function useTabs(items: TabItem[], defaultIndex = 0) {
const uid = useId();
const [activeIndex, setActiveIndex] = useState(defaultIndex);
const getTabId = (i: number) => `${uid}-tab-${i}`;
const getPanelId = (i: number) => `${uid}-panel-${i}`;
const handleKeyDown = (e: React.KeyboardEvent, i: number) => {
const enabledIndices = items
.map((item, idx) => (!item.disabled ? idx : null))
.filter((x): x is number => x !== null);
const pos = enabledIndices.indexOf(i);
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
e.preventDefault();
const next = enabledIndices[(pos + 1) % enabledIndices.length];
setActiveIndex(next);
} else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
e.preventDefault();
const prev = enabledIndices[(pos - 1 + enabledIndices.length) % enabledIndices.length];
setActiveIndex(prev);
} else if (e.key === 'Home') {
e.preventDefault();
setActiveIndex(enabledIndices[0]);
} else if (e.key === 'End') {
e.preventDefault();
setActiveIndex(enabledIndices[enabledIndices.length - 1]);
}
};
return { activeIndex, setActiveIndex, getTabId, getPanelId, handleKeyDown };
}Worth noting: useId() landed in React 18.0 and is the right tool here - it generates stable, server-safe IDs so your ARIA attributes survive SSR without hydration mismatches. Don't roll your own UUID for this.
The handleKeyDown implementation above skips disabled tabs in the rotation, which is the behavior users actually expect. A lot of implementations get this wrong and trap focus on disabled items.
Underline Variant
The underline tab is the most universal. A horizontal row of text labels, a colored underline slides to the active tab. Simple, works in almost any design system, reads clearly at 14px or 16px. This is what you reach for in dashboards, documentation sites, and content areas.
// UnderlineTabs.tsx
import { useTabs, TabItem } from './useTabs';
export function UnderlineTabs({ items }: { items: TabItem[] }) {
const { activeIndex, setActiveIndex, getTabId, getPanelId, handleKeyDown } = useTabs(items);
return (
<div>
<div role="tablist" className="flex border-b border-gray-200 dark:border-gray-700">
{items.map((item, i) => (
<button
key={item.id}
id={getTabId(i)}
role="tab"
aria-selected={activeIndex === i}
aria-controls={getPanelId(i)}
aria-disabled={item.disabled}
tabIndex={activeIndex === i ? 0 : -1}
disabled={item.disabled}
onClick={() => !item.disabled && setActiveIndex(i)}
onKeyDown={(e) => handleKeyDown(e, i)}
className={[
'px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors',
activeIndex === i
? 'border-indigo-500 text-indigo-600'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300',
item.disabled ? 'opacity-40 cursor-not-allowed' : 'cursor-pointer',
].join(' ')}
>
{item.label}
</button>
))}
</div>
{items.map((item, i) => (
<div
key={item.id}
id={getPanelId(i)}
role="tabpanel"
aria-labelledby={getTabId(i)}
hidden={activeIndex !== i}
className="pt-4"
>
{item.content}
</div>
))}
</div>
);
}The -mb-px on each tab button and border-b on the container is the classic trick: the active tab's border-b-2 sits exactly on top of the container border, making it look like a continuous line with a colored segment. Honestly, it's one of those CSS micro-tricks that looks clever until you realize it's in every design system from 2014 onward.
One more thing - using hidden on the panel instead of conditional rendering keeps all panel content in the DOM. That means form state, scroll positions, and lazy-loaded content survive tab switches. If your panels are very heavy, switch to conditional render and accept the reset behavior.
Pills Variant
Pills work better than underlines when tabs live inside a card, a sidebar, or any surface that doesn't have a natural bottom edge to anchor the underline to. They're also visually heavier - good for primary navigation in a tool or settings panel, bad for a subtle filter row inside a table.
// PillTabs.tsx
import { useTabs, TabItem } from './useTabs';
export function PillTabs({ items }: { items: TabItem[] }) {
const { activeIndex, setActiveIndex, getTabId, getPanelId, handleKeyDown } = useTabs(items);
return (
<div>
<div
role="tablist"
className="inline-flex gap-1 rounded-xl bg-gray-100 dark:bg-gray-800 p-1"
>
{items.map((item, i) => (
<button
key={item.id}
id={getTabId(i)}
role="tab"
aria-selected={activeIndex === i}
aria-controls={getPanelId(i)}
tabIndex={activeIndex === i ? 0 : -1}
disabled={item.disabled}
onClick={() => !item.disabled && setActiveIndex(i)}
onKeyDown={(e) => handleKeyDown(e, i)}
className={[
'px-4 py-1.5 rounded-lg text-sm font-medium transition-all',
activeIndex === i
? 'bg-white dark:bg-gray-700 shadow text-gray-900 dark:text-white'
: 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300',
item.disabled ? 'opacity-40 cursor-not-allowed' : '',
].join(' ')}
>
{item.label}
</button>
))}
</div>
{items.map((item, i) => (
<div
key={item.id}
id={getPanelId(i)}
role="tabpanel"
aria-labelledby={getTabId(i)}
hidden={activeIndex !== i}
className="mt-4"
>
{item.content}
</div>
))}
</div>
);
}Quick aside: if you want the active pill to animate with a sliding background instead of just toggling classes, reach for Framer Motion's <motion.div layoutId="pill" /> behind the active button. It picks up the position and size automatically - no manual offset math. But that's a 40 KB dependency for what amounts to a cosmetic detail, so weigh it carefully.
The pill style pairs especially well with glassmorphism surfaces. If you're building that kind of premium feel, check out Empire UI's glassmorphism components - several of them include tabs already styled inside glass cards, so you're not stitching two things together.
Scrollable Tabs for Mobile
Here's the scenario: you've got 8 category tabs, your designer refuses to drop any of them, and you need it to work on a 375px iPhone screen. Wrapping makes it ugly. Truncating labels is a UX crime. The right answer is a horizontally scrollable tab bar - overflow-x scroll, snap-scrolling optional, scroll-into-view on activation.
// ScrollableTabs.tsx
import { useTabs, TabItem } from './useTabs';
import { useRef, useEffect } from 'react';
export function ScrollableTabs({ items }: { items: TabItem[] }) {
const { activeIndex, setActiveIndex, getTabId, getPanelId, handleKeyDown } = useTabs(items);
const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
const listRef = useRef<HTMLDivElement>(null);
// Scroll active tab into view
useEffect(() => {
const activeTab = tabRefs.current[activeIndex];
if (activeTab && listRef.current) {
activeTab.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
}
}, [activeIndex]);
return (
<div>
<div
ref={listRef}
role="tablist"
className="flex overflow-x-auto gap-0 border-b border-gray-200 scrollbar-none"
style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
>
{items.map((item, i) => (
<button
key={item.id}
ref={(el) => { tabRefs.current[i] = el; }}
id={getTabId(i)}
role="tab"
aria-selected={activeIndex === i}
aria-controls={getPanelId(i)}
tabIndex={activeIndex === i ? 0 : -1}
disabled={item.disabled}
onClick={() => !item.disabled && setActiveIndex(i)}
onKeyDown={(e) => handleKeyDown(e, i)}
className={[
'flex-shrink-0 px-5 py-2.5 text-sm font-medium border-b-2 -mb-px whitespace-nowrap transition-colors',
activeIndex === i
? 'border-indigo-500 text-indigo-600'
: 'border-transparent text-gray-500 hover:text-gray-700',
].join(' ')}
>
{item.label}
</button>
))}
</div>
{items.map((item, i) => (
<div
key={item.id}
id={getPanelId(i)}
role="tabpanel"
aria-labelledby={getTabId(i)}
hidden={activeIndex !== i}
className="pt-4"
>
{item.content}
</div>
))}
</div>
);
}flex-shrink-0 and whitespace-nowrap on each tab are non-negotiable - without them, tabs will wrap or compress instead of overflowing. The scrollIntoView call on activeIndex change is what makes keyboard navigation feel right on mobile; without it, you can arrow-key your way to a tab that's off-screen and have no visual feedback.
In practice, adding fade gradients on the left and right edges of the scroll container is worth the 10 extra lines. Users often don't realize a container is scrollable unless there's a visual cue. A ::after pseudo-element with background: linear-gradient(to right, transparent, white) pinned to the right edge does the job. You'd need Tailwind's arbitrary properties or a small inline style for this since pseudo-elements aren't in the utility API.
Look, this variant is where most component libraries cut corners. They give you overflow-scroll and call it done, with no scroll-into-view, no fade hints, no touch momentum. If that gap bothers you, browse the Empire UI component library - the scrollable tabs there handle all three out of the box.
Vertical Tabs
Vertical tabs show up in settings pages, admin panels, and anything structured like a sidebar-plus-content layout. The tab list runs down the left (or right), the panel fills the rest of the space. The ARIA pattern changes slightly: Arrow Up/Down navigate tabs instead of Arrow Left/Right, which the useTabs hook already handles - both axis events are wired up.
// VerticalTabs.tsx
import { useTabs, TabItem } from './useTabs';
export function VerticalTabs({ items }: { items: TabItem[] }) {
const { activeIndex, setActiveIndex, getTabId, getPanelId, handleKeyDown } = useTabs(items);
return (
<div className="flex gap-0">
{/* Tab list */}
<div
role="tablist"
aria-orientation="vertical"
className="flex flex-col w-48 flex-shrink-0 border-r border-gray-200 dark:border-gray-700"
>
{items.map((item, i) => (
<button
key={item.id}
id={getTabId(i)}
role="tab"
aria-selected={activeIndex === i}
aria-controls={getPanelId(i)}
tabIndex={activeIndex === i ? 0 : -1}
disabled={item.disabled}
onClick={() => !item.disabled && setActiveIndex(i)}
onKeyDown={(e) => handleKeyDown(e, i)}
className={[
'px-4 py-2.5 text-sm font-medium text-left border-r-2 -mr-px transition-colors',
activeIndex === i
? 'border-indigo-500 text-indigo-600 bg-indigo-50 dark:bg-indigo-900/20'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800',
item.disabled ? 'opacity-40 cursor-not-allowed' : '',
].join(' ')}
>
{item.label}
</button>
))}
</div>
{/* Panels */}
<div className="flex-1 pl-6">
{items.map((item, i) => (
<div
key={item.id}
id={getPanelId(i)}
role="tabpanel"
aria-labelledby={getTabId(i)}
hidden={activeIndex !== i}
>
{item.content}
</div>
))}
</div>
</div>
);
}The aria-orientation="vertical" attribute on the tablist is something almost every tutorial skips. Screen readers use it to announce whether arrow keys navigate horizontally or vertically - get this wrong and keyboard users get confused. It's one attribute, just add it.
Worth noting: vertical tabs on mobile are almost always wrong. A 192px sidebar (w-48) on a 375px screen leaves 183px for content - barely enough for a form field. Either collapse to horizontal tabs below a breakpoint or switch to a select dropdown. The responsive collapse looks like: <div className="hidden md:flex md:flex-col"> on the tab list, with a <select> shown below md.
Pair this layout with the box shadow generator to add depth between the tab list and panel - a subtle right shadow on the list creates a nice card-like separator without a hard border.
Putting It Together: A Tabbed Settings Page
Here's a realistic usage example showing how you'd wire all this up in a Next.js settings page. This is the pattern you'd actually encounter on a project, not a toy demo with three placeholder panels.
// app/settings/page.tsx
import { VerticalTabs, TabItem } from '@/components/tabs';
import { ProfileSettings } from './ProfileSettings';
import { BillingSettings } from './BillingSettings';
import { NotificationSettings } from './NotificationSettings';
import { SecuritySettings } from './SecuritySettings';
const SETTINGS_TABS: TabItem[] = [
{ id: 'profile', label: 'Profile', content: <ProfileSettings /> },
{ id: 'billing', label: 'Billing', content: <BillingSettings /> },
{ id: 'notifications', label: 'Notifications', content: <NotificationSettings /> },
{ id: 'security', label: 'Security', content: <SecuritySettings /> },
{ id: 'danger', label: 'Danger Zone', content: <div>...</div> },
];
export default function SettingsPage() {
return (
<main className="max-w-4xl mx-auto px-6 py-12">
<h1 className="text-2xl font-bold mb-8">Settings</h1>
<VerticalTabs items={SETTINGS_TABS} />
</main>
);
}Notice the tab items array is defined outside the component. This matters. If you define it inside, you get a new array reference on every render, which can cause unnecessary re-renders in child components memoized with React.memo. Keep static data static.
If you need the active tab to sync with the URL - so users can deep-link to /settings?tab=billing - replace the internal useState in useTabs with a URL-driven variant using useSearchParams from Next.js 13+. The rest of the component stays identical. That's the payoff of the hook abstraction.
Looking for more component patterns like this? The animated tabs in Empire UI includes a motion-animated indicator, controlled and uncontrolled modes, icon support, and a badge variant - all styled across every visual theme from neobrutalism to cyberpunk.
FAQ
The container needs role="tablist", each button gets role="tab" with aria-selected and aria-controls, and each panel gets role="tabpanel" with aria-labelledby. Skip any of these and screen readers won't understand the relationship between tabs and content.
Handle Arrow Left/Right (or Up/Down for vertical tabs) in onKeyDown to move focus between tabs, and use tabIndex={isActive ? 0 : -1} on each button so only the active tab is in the natural tab order. The Home and End keys should jump to the first and last enabled tab.
Use hidden attribute if you need to preserve state (form inputs, scroll position, loaded data) across tab switches. Use conditional rendering if panels are heavy and you want to avoid mounting everything upfront - just accept that state resets when tabs change.
Replace the useState in your tabs hook with useSearchParams to read the current tab, and router.push or router.replace to update it on change. The visual component doesn't need to change at all - only the state source changes.