react-native-paper
react-native-paper copied to clipboard
feat: add generic type support to ToggleButton components
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
forwardReflimitations 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
- 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>
- Verify
reftyping still works correctly with the new custom type forToggleButton
Hey @faciledictu, thank you for your pull request 🤗. The documentation from this branch can be viewed here.