Platform-Specific Code

Also called Platform module, Platform.select

Updated

What is Platform-Specific Code in React Native?

Platform-specific code lets one codebase behave differently per platform, via the Platform module or file extensions like Button.ios.tsx that Metro resolves.

iOSAndnever shippedmain.jsbundle
In this platform’s bundleSource fileGate set to the platformMetro builds one bundle per platform. Import ./Picker and it resolves to Picker.ios.tsx in the iOS bundle and Picker.android.tsx in the Android one, so the other platform's file is never shipped. Platform.select, for small differences like a shadow against an elevation, ships in both bundles and picks its branch at runtime by Platform.OS. Reach for either when the platform convention really differs, not to paper over a layout bug.

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.