Skip to main content

Platform-Specific Code

There are two ways to write code for one platform. File extensions (Button.ios.tsx, Button.android.tsx) let the bundler (Metro) pick the right file at build time; use them when the implementations differ a lot. The Platform module (Platform.OS, Platform.select, Platform.Version) branches at runtime; use it for small differences.

Applies to: React Native 0.88, Expo SDK 58.

Details​

File Extensions​

FilePicked up by
Component.ios.tsxiOS build
Component.android.tsxAndroid build
Component.native.tsxiOS and Android, when there is no .ios / .android file
Component.web.tsxWeb build (React Native Web)
Component.tsxAny platform without a more specific file

Import without the extension: import Component from './Component'. The other platform's file is not included in the bundle.

Platform Module​

APIWhat it gives
Platform.OS'ios', 'android', 'web', …
Platform.select({})The value for the current platform; keys ios, android, native, web, default
Platform.VersionAndroid: API level as a number (34); iOS: system version as a string ('26.0')
Platform.isPadiOS only: the device is an iPad

Example​

import { Platform, StyleSheet, PermissionsAndroid } from 'react-native';

const styles = StyleSheet.create({
code: {
padding: Platform.OS === 'ios' ? 20 : 10,
fontFamily: Platform.select({
ios: 'Menlo',
android: 'monospace',
default: 'monospace',
}),
},
});

// Runtime permission for notifications exists since Android 13 (API 33)
async function askNotificationPermission() {
if (Platform.OS === 'android' && Platform.Version >= 33) {
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
);
}
}

Follow-up Questions​

  • What ends up in the bundle? Only the matching platform file; in release builds Metro also removes Platform.OS and Platform.select branches for other platforms when Platform is imported directly from react-native.
  • Where does native configuration go in an Expo app? The ios and android keys and config plugins in app.json, not hand-edited ios/ and android/ folders.

Common Mistakes​

  • Platform.select without default: it returns undefined on web and other platforms.

See Also​