Platform-Specific Code
Also called Platform module, Platform.select
- Part of
- React Native Glossary
- Also known as
- Platform module, Platform.select
- Mentioned in
- Metro
- Updated
What is Platform-Specific Code in React Native?
Platform-specific code lets one codebase behave differently per platform, through the Platform module or file extensions such as Button.ios.tsx that Metro resolves automatically.
React Native shares most code across platforms, but not all of it should be shared — a shadow, a haptic, or a date picker often needs to differ. There are two supported mechanisms.
The Platform module, for small branches:
import { Platform } from 'react-native';
const styles = {
padding: Platform.OS === 'ios' ? 12 : 16,
...Platform.select({ ios: { shadowOpacity: 0.1 }, android: { elevation: 4 } }),
};
Platform file extensions, for whole components. Create Picker.ios.tsx and Picker.android.tsx, then import ./Picker — Metro picks the right file at bundle time, so the other platform's code is never shipped.
Platform.Version gives the OS version when you need to gate on an API level.
The judgement call for newcomers: reach for this when the platform convention genuinely differs, not to paper over a layout bug. Excessive branching is how a cross-platform codebase quietly becomes two codebases. See platform-specific code.