TechnicalEasy React Native

How do you write platform-specific code in React Native?

Asked for Mobile Developer

Why they ask this: Android and iOS differ in many details, and real apps must handle both.

Answer

  1. The Platform module for small differences:
jsx
import { Platform, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  header: {
    paddingTop: Platform.OS === 'ios' ? 44 : 0,
    ...Platform.select({
      ios: { shadowOpacity: 0.2, shadowRadius: 4 },
      android: { elevation: 4 },
    }),
  },
});
  1. Platform-specific files for bigger differences: DatePicker.ios.tsx and DatePicker.android.tsx. Importing ./DatePicker picks the right file automatically.
  2. Native modules (Kotlin/Java or Swift/Objective-C), or Expo modules, when you need an API that JavaScript cannot reach.

Prefer safe-area handling (react-native-safe-area-context) over hard-coded paddings for notches.

Can you explain this in your own words?

Back to question bank