Skip to main content

Overview

The Switch component provides pattern matching for conditional rendering, similar to JavaScript’s switch statement. It supports both value-based matching and boolean condition matching.

Import

Component Parts

Switch.Root

The root component that controls which case to render

Switch.Match

Defines a case to potentially render

Switch.Default

Defines the default case when no match is found

Switch.Root

Props

React.ReactElement | React.ReactElement[]
required
Must contain Switch.Match components and optionally one Switch.Default.
TValue
The value to match against. When provided, works like switch(value). When omitted, works like switch(true) and matches the first truthy when prop.

Switch.Match

Props

false | TWhen | null | undefined
required
The condition to match. In value mode, this is compared with the root’s value. In boolean mode, the first truthy when is rendered.
React.ReactNode | ((value: TWhen) => React.ReactNode)
required
Content to render when matched. Can be a render function that receives the matched value.

Switch.Default

Props

React.ReactNode
required
Content to render when no match is found.

Usage Examples

Value-Based Matching

Boolean Mode (switch true)

With Render Functions

Numeric Values

Complex Conditions

Nested Switches

Without Default

First Match Wins

Notes

  • When value is provided, it works like switch(value) matching against each when prop
  • When value is omitted, it works like switch(true) rendering the first truthy when
  • Only one Switch.Default component is allowed
  • First matching case wins (short-circuits like a real switch statement)
  • Render functions receive the matched value with proper TypeScript narrowing
  • Returns null if no match is found and no default is provided
  • All comparisons use strict equality (===) in value mode