When to Use
- Render different content based on multiple mutually exclusive conditions
- Implement pattern matching in React components
- Replace long chains of if-else or ternary operators
- Handle state machines with different states
- Provide default fallback for unmatched cases
Basic Usage
Component API
Switch.Root
Container that evaluates and renders the first matching case.TValue
Value to match against. If omitted, switches to boolean matching mode (like
switch(true))SwitchMatchElement | SwitchMatchElement[]
required
Switch.Match and Switch.Default components to evaluate
Switch.Match
Defines a case to match against.TWhen | false | null | undefined
required
Value to match (in value mode) or condition to evaluate (in boolean mode)
React.ReactNode | ((value: TWhen) => React.ReactNode)
required
Content to render when matched. Can be a render function receiving the matched value
Switch.Default
Defines fallback content when no cases match.React.ReactNode
required
Fallback content to display
Examples
API Response States
User Role Rendering
Complex Condition Matching
Theme Selector
With Render Functions
Order Status Flow
Comparison to Native Patterns
Multiple Ternaries
If-Else Chain
With Switch Component
Common Use Cases
Form Step Navigation
File Type Preview
When no
value prop is provided, Switch works like switch(true) in JavaScript, evaluating each when condition until it finds a truthy one.Only the first matching
Switch.Match is rendered. Once a match is found, remaining cases are skipped.