react-native-paper icon indicating copy to clipboard operation
react-native-paper copied to clipboard

feat: add generic type support to ToggleButton components

Open faciledictu opened this issue 6 months ago • 1 comments

Motivation

ToggleButton and ToggleButtonRow components only supported string values, causing TypeScript errors when developers tried to use numbers, enums, or custom types. ToggleButtonGroup was already generic but ToggleButtonRow weren't.

// ❌ TypeScript error with numbers
<ToggleButton value={42} onPress={(v: number) => {}} />
// Error: Type 'number' is not assignable to type 'string'.ts(2322)

// Error: Type '(v: number) => number' is not assignable to type '(value?: string | GestureResponderEvent | undefined) => void'.

Changes

  • Made ToggleButtonRow generic (same as ToggleButtonGroup)
  • Made ToggleButton generic with custom wrapper to preserve forwardRef I had to introduce a custom type wrapper to avoid forwardRef limitations with generics.
  • Exported ToggleButtonContextType for proper type inference
  • All three components work together seamlessly
  • No breaking changes to existing examples

Related issue

#3920

Test plan

  1. Verify TypeScript compilation with different value types:
// Test with numbers
<ToggleButton value={42} onPress={(v?: GestureResponderEvent | number) => ...} />

// Test with enums/union types
type Theme = 'light' | 'dark' | 'auto';
<ToggleButton value="light" onPress={(v?: GestureResponderEvent | Theme) => ...} />

// Test with complex objects
<ToggleButton value={{id: 1, label: 'High'}} onPress={(v?: GestureResponderEvent | Priority) => ...} />

// Test ToggleButton.Row
<ToggleButton.Row value={fontSize} onValueChange={(v: number) => setFontSize(v)}>
  <ToggleButton value={12} />
  <ToggleButton value={16} />
  <ToggleButton value={20} />
</ToggleButton.Row>
  1. Verify ref typing still works correctly with the new custom type for ToggleButton

faciledictu avatar Sep 13 '25 11:09 faciledictu

Hey @faciledictu, thank you for your pull request 🤗. The documentation from this branch can be viewed here.

callstack-bot avatar Sep 13 '25 11:09 callstack-bot