Skip to the workspace
Pebellslearn by building
Lists and Platform-Specific Code  ›  Capstone Project

Platform Differences in Code

Platform Module 12 minUse Platform.OS and Platform.select for small differences, platform file extensions like .ios.js and .android.js for whole components that differ, and react-native-web to reach the browser.

react native / Platform Differences in Code

Explore each scene at your own pace.

01 · The rule

The rule

Platform Differences in Code

Most of Sprout is shared, but a few details should differ. iPhone users expect a subtle shadow; Android uses elevation. The date picker looks different on each. React Native gives you three levels of tools for this, from a single value to a whole file, and even a path to the web.

The rule

Small difference, Platform; big difference, separate files.

The Platform module handles small differences inside one file:

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

const styles = StyleSheet.create({
  card: {
    padding: 16,
    ...Platform.select({
      ios: { shadowOpacity: 0.15, shadowRadius: 6 },
      android: { elevation: 3 },
      default: {},
    }),
  },
});

if (Platform.OS === 'android') {
  // Android-only behaviour
}
  • Platform.OS is 'ios', 'android' or 'web' (and a few others).
  • Platform.select({...}) returns the value for the current platform, with default as the fallback.
  • Platform.Version gives the OS version: a number (the API level) on Android, a string on iOS.

Platform file extensions handle big differences. Create two files with the same base name:

components/DatePicker.ios.js
components/DatePicker.android.js

Then import without the extension:

import DatePicker from './components/DatePicker';

Metro picks the right file for each platform when it bundles. There is also .native.js, used for iOS and Android together, next to a plain .js that the web build uses.

react-native-web runs React Native components in a browser by turning View and Text into HTML elements. Expo uses it for its web target, which is why Platform.OS can be 'web'. Features without a browser equivalent need a web branch or a .web.js file.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.