Lesson 6 / 25

Platform-Specific Code

When iOS and Android should differ.

Platform.OS, Platform.select and file extensions

Most code is shared, but sometimes platforms need different behaviour or looks. The Platform module exposes Platform.OS ("ios", "android" or "web") and Platform.select, which picks a value from an object keyed by platform with an optional default. For larger differences, create platform-specific files: Button.ios.tsx and Button.android.tsx, then import ./Button; the Metro bundler picks the right file for each platform. Shadows are a classic example: iOS has historically used shadow* props while Android used elevation; newer versions add a cross-platform boxShadow style, so check the docs for your version.

Platform.select for a card shadow

One style object, two platforms.

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

export const styles = StyleSheet.create({
  card: {
    borderRadius: 12,
    backgroundColor: "white",
    ...Platform.select({
      ios: {
        shadowColor: "#000",
        shadowOpacity: 0.1,
        shadowRadius: 8,
        shadowOffset: { width: 0, height: 4 },
      },
      android: { elevation: 4 },
      default: {},
    }),
  },
});

// Larger differences: DatePicker.ios.tsx and DatePicker.android.tsx,
// imported as: import DatePicker from "./DatePicker";

Follow each platform's conventions

Users expect platform behaviour such as the Android back button and iOS swipe-back gestures. Navigation libraries handle many of these for you when you use their native stacks.

Quick check: How do you give iOS and Android different implementations of the same component file?

  • Add a CSS media query for each OS
  • Wrap the file in a Platform component
  • Use two separate repositories
  • Create Component.ios.tsx and Component.android.tsx and import ./Component
Answer

Create Component.ios.tsx and Component.android.tsx and import ./Component — Metro resolves platform extensions automatically.