CodeBlanks Logo Icon CodeBlanks

Platform-specific

Learn platform-specific native modules.

Platform-specific

Platform-specific code is writing different behavior for iOS and Android. The Platform module gives the device's OS: Platform.OS === 'ios' or Platform.OS === 'android'. You branch based on this.

File names can also be platform-selective: Battery.ios.js is loaded only on iOS, Battery.android.js only on Android. Battery.js is used as a fallback on both. This pattern is preferred when the differences are big; for small differences Platform.OS is more practical.

Branching with Platform.OS

Platform.OS is a string: 'ios' or 'android'. You write iOS-specific code with if (Platform.OS === 'ios'). This pattern is ideal for small differences: margin values, colors, behavior differences.

Example: const marginTop = Platform.OS === 'ios' ? 40 : 24. On iOS 40 may be needed due to the notch; on Android 24 px may be enough. This single-line solution is more practical than creating two separate files.

Practice Platform margin value

Complete the getTopMargin function. Import Platform from react-native. Return Platform.OS === 'ios' ? 40 : 24.

Starter code

App.js
import { Platform } from 'react-native';

export function getTopMargin() {
  // return 40 or 24 based on Platform.OS
}

Sample solution

App.js
import { Platform } from 'react-native';

export function getTopMargin() {
  return Platform.OS === 'ios' ? 40 : 24;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Import Platform

Question
import { ____ } from 'react-native';
Answer
import { Platform } from 'react-native';

Explanation: The Platform module gives the OS.

2 Match the platform parts

Term Meaning
Platform.OS Operating system
'ios' iOS value
'android' Android value
.ios.js iOS file extension

3 Which is ideal for small differences?

  • Creating two separate files Correct answer
  • Branching with Platform.OS
  • Writing a native module
  • Installing a new package

Explanation: Branching with Platform.OS is ideal for small differences.

All lessons in Advanced