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
- The
Platformmodule 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 },
}),
},
});- Platform-specific files for bigger differences:
DatePicker.ios.tsxandDatePicker.android.tsx. Importing./DatePickerpicks the right file automatically. - 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?
Related questions
- EasyHow does React Native work, and how is it different from Flutter and fully native development?
- EasyWhen should you use FlatList instead of ScrollView in React Native?
- MediumHow do you store data locally in a React Native app?
- MediumHow do you find and fix performance problems in a React Native app?