patterntypescriptreact-nativeTip
Platform-Specific Code: .ios.tsx / .android.tsx File Extensions
Viewed 0 times
platform specificios extensionandroid extensionMetro bundlerPlatform.selectcross-platform
Problem
Managing platform differences with many
Platform.OS === 'ios' checks in a single file makes components hard to read and maintain.Solution
Use platform-specific file extensions:
Component.ios.tsx and Component.android.tsx. The Metro bundler automatically picks the correct file. For smaller differences, use Platform.select({ ios: ..., android: ... }) inline. For web, add .web.tsx.Why
Metro bundler resolves module imports by checking for platform-suffixed files first. This provides a clean separation without runtime conditionals, enabling complete native implementations per platform.
Gotchas
- Types must be identical across platform files — TypeScript does not automatically merge their types
- Barrel exports (index.ts) that re-export platform-specific components need their own index.ios.ts / index.android.ts or a runtime check
- Platform.select is evaluated at runtime, not compile time — bundle both branches are included
- Web (
.web.tsx) is only meaningful if you are using React Native for Web
Code Snippets
Platform-specific module via file extension
// Haptics.ios.tsx
import * as Haptics from 'expo-haptics';
export const triggerHaptic = () => Haptics.impactAsync();
// Haptics.android.tsx
export const triggerHaptic = () => { /* vibration alternative */ };
// Usage (Metro picks the right file automatically)
import { triggerHaptic } from './Haptics';
triggerHaptic();Revisions (0)
No revisions yet.