Skip to main content

Working with Platform-Specific Code

1. Using Platform.OS

Property Description Values
Platform.OS Identifies the platform at runtime "ios", "android", "web"

Example: Detecting Platform

import { Platform } from 'react-native';

const isIOS = Platform.OS === 'ios';
const isAndroid = Platform.OS === 'android';

console.log("Running on:", Platform.OS);
Note: Platform.OS is a string literal that can be used for conditional rendering or logic branching.

2. Using Platform.select Method

Platform Value Description
Platform.OS "ios" or "android" String indicating the operating system
Platform.select object Function to conditionally render components or styles based on platform

Example: Using Platform.select for Conditional Rendering

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

const MyComponent = () => {
  return (
    <Text style={{
      fontSize: Platform.select({
        ios: 16,
        android: 14,
      }),
    }}>
      Hello World
    </Text>
  );
};

Example: Using Platform.select for Component Differences

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

const MyComponent = () => {
  const platformSpecificComponent = Platform.select({
    ios: () => <View></View>,
    android: () => <View></View>,
  })();

  return platformSpecificComponent;
};
Note: Platform.select is useful for rendering different components or applying different styles depending on the platform. It supports all platforms that React Native supports, including ios, android, web, and macos.

3. Creating Platform-specific Files

Example: Platform-specific file naming

// File structure for platform-specific code
MyComponent.js          // Shared code
MyComponent.android.js  // Android-specific implementation
MyComponent.ios.js      // iOS-specific implementation
MyComponent.web.js      // Web-specific implementation
File Extension Platform Description
.android.js Android Platform-specific implementation for Android devices
.ios.js iOS Platform-specific implementation for iOS devices
.web.js Web Platform-specific implementation for web browsers
Note: React Native automatically selects the correct file based on the platform at build time.
Warning: Ensure that shared components have matching APIs across platform-specific files to maintain consistent behavior.

4. Using Platform.Version

Property Description Notes
Platform.Version String representing the version of the operating system Available on both iOS and Android platforms

Example: Checking Platform Version

import { Platform } from 'react-native';

const version = Platform.Version;
console.log('OS Version: ', version);
Note: The value of Platform.Version varies by platform and OS version. On iOS, it returns a string like "14.0", while on Android, it returns a numeric string like "21" (API level).

5. Handling Platform-specific Styles

Platform Style Property Description
iOS shadowColor Color of the shadow
iOS shadowOffset Offset of the shadow (width, height)
iOS shadowOpacity Opacity of the shadow
iOS shadowRadius Radius of the shadow
Android elevation Shadow elevation (higher = more shadow)
Android backgroundColor Background color of the view

Example: Platform-specific style properties

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

const styles = StyleSheet.create({
  box: {
    width: 100,
    height: 100,
    backgroundColor: '#f0f0f0',
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
      },
      android: {
        elevation: 5,
        backgroundColor: '#f0f0f0',
      },
    }),
  },
});
Note: Use Platform.select() to apply different styles for iOS and Android.

6. Implementing Conditional Rendering

Example: Conditional rendering with ternary operator

import React, { useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

const ConditionalExample = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <View>
      {isLoggedIn ? (
        <Text>Welcome back!</Text>
      ) : (
        <Text>Please log in.</Text>
      )}
    </View>
  );
};

export default ConditionalExample;
Method Description Usage
Ternary Operator Shorthand for if-else logic condition ? <ComponentA /> : <ComponentB />
Logical AND (&&) Renders component only if condition is truthy condition && <Component />
If-Else Block Useful for complex conditions if (condition) { <Component /> }
Note: Conditional rendering in React Native works the same as in React, but always consider performance implications when rendering large components conditionally.

7. Using PlatformColor

Property Description Usage
PlatformColor Provides a way to access platform-specific colors in React Native. const color = PlatformColor('systemBlue');

Example: Using PlatformColor

import { PlatformColor } from 'react-native';\n\nconst styles = {\n  text: {\n    color: PlatformColor('systemBlue'),\n  },\n  background: {\n    backgroundColor: PlatformColor('systemGray'),\n  }\n};
Note: PlatformColor is only available on iOS and Android platforms.

8. Handling Platform-specific APIs

API Platform Description Usage
StatusBar Android, iOS Control the status bar visibility and appearance {'import { StatusBar } from "react-native";\n\nStatusBar.setHidden(true);'}
PermissionsAndroid Android Request and check runtime permissions {'import { PermissionsAndroid } from "react-native";\n\nconst requestCameraPermission = async () => {\n try {\n const granted = await PermissionsAndroid.request(\n PermissionsAndroid.PERMISSIONS.CAMERA,\n {\n title: "Camera Permission",\n message: "App needs camera access",\n }\n );\n if (granted === PermissionsAndroid.RESULTS.GRANTED) {\n console.log("Camera permission granted");\n } else {\n console.log("Camera permission denied");\n }\n } catch (err) {\n console.warn(err);\n }\n};'}
StatusBarIOS iOS Control status bar on iOS (deprecated, use StatusBar) {'import { StatusBarIOS } from "react-native";\n\nStatusBarIOS.setStyle("light-content");'}
Note: Use Platform module to conditionally render components or call platform-specific APIs.
{'import { Platform, StyleSheet } from "react-native";\n\nconst styles = StyleSheet.create({\n  container: {\n    ...,\n    paddingTop: Platform.OS === "ios" ? 20 : 0\n  }\n});'} 

9. Creating Universal Components

Example: Platform-specific component rendering

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

const UniversalComponent = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>
        {Platform.OS === 'ios' ? 'iOS specific content' : 'Android specific content'}
      </Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  text: {
    fontSize: 18
  }
});

export default UniversalComponent;
Property Description Usage
Platform.OS String indicating the operating system Used to conditionally render components or apply styles
Platform.select() Object with keys for each platform Allows conditional rendering based on the platform

Example: Using Platform.select()

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

const UniversalComponent = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>
        {Platform.select({
          ios: 'This is iOS',
          android: 'This is Android',
          default: 'Default text for other platforms'
        })}
      </Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  text: {
    fontSize: 18
  }
});

export default UniversalComponent;
Note: Platform-specific code should be used sparingly. Prefer universal components that work across platforms when possible.

10. Testing Platform-specific Code

Example: Platform-specific test setup

import { Platform } from 'react-native';
import { jest } from '@jest/globals';

// Mock platform for testing
jest.spyOn(Platform, 'OS', 'get').mockReturnValue('ios');

// Test iOS-specific logic
test('renders iOS-specific component', () => {
  const { getByText } = render(<MyComponent />);
  expect(getByText('iOS Title')).toBeTruthy();
});
Platform Testing Method Notes
ios Platform.OS === 'ios' Use Platform.OS to detect iOS
android Platform.OS === 'android' Use Platform.OS to detect Android
web Platform.OS === 'web' Use Platform.OS to detect web platform

Testing Platform-specific Code

  • Use Platform.OS to detect the current platform
  • Mock Platform.OS in tests to simulate different platforms
  • Write platform-specific tests using conditional rendering logic
  • Use Jest's spyOn to mock platform detection

Was this article helpful?