Radix UI Tabs Controlled Not Working — Fix Active Tab
In this fix, you'll learn how to control Radix UI Tabs programmatically. This matters for tab navigation with sync, and appears in settings pages and profile sections.
The Problem
The following code demonstrates the typical mistake:
<Tabs defaultValue="account">
<TabsList>
<TabsTrigger value="account">Account</TabsTrigger>
<TabsTrigger value="password">Password</TabsTrigger>
</TabsList>
<TabsContent value="account">Account settings</TabsContent>
<TabsContent value="password">Password settings</TabsContent>
</Tabs>
// Works but can't programmatically change tabs
The Fix
Here is the corrected version:
const [tab, setTab] = useState('account');
<Tabs value={tab} onValueChange={setTab}>
<TabsList>
<TabsTrigger value="account">Account</TabsTrigger>
<TabsTrigger value="password">Password</TabsTrigger>
</TabsList>
<TabsContent value="account">Account settings</TabsContent>
<TabsContent value="password">Password settings</TabsContent>
</Tabs>
// Programmatically: setTab('password')
// Tab content switches programmatically
Prevention
- Use value and onValueChange for controlled tabs.
- Use defaultValue for uncontrolled tabs (initial state only).
- The value string must match a TabsTrigger's value prop.
- TabsContent with matching value renders when the tab is active.
- Use URL search params to persist tab state across navigation.
Common Mistakes with ui tabs controlled
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world RADIX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro