← Back to Chapters

Platform-Specific Code in React Native

? Platform-Specific Code in React Native

? Quick Overview

React Native allows developers to write a single codebase for multiple platforms. However, sometimes platform-specific behavior is required. React Native provides multiple ways to handle differences between Android, iOS, and other platforms.

? Key Concepts

  • Platform module for runtime checks
  • Platform-specific file extensions
  • Conditional styling and logic
  • Native platform APIs

? Syntax / Theory

Platform-specific code helps you customize behavior, UI, or logic depending on the operating system. This ensures a native look and feel while still sharing most of the code.

? View Code Example
// Import Platform API from react-native
import { Platform } from "react-native";

const osName = Platform.OS;
console.log(osName);

? Code Example(s)

? View Code Example
// Conditional rendering based on platform
import { Text, Platform } from "react-native";

function MyComponent() {
  if (Platform.OS === "android") {
    return <Text>Android Device</Text>;
  }
  return <Text>iOS Device</Text>;
}

? Live Output / Explanation

Output Explanation

The component checks the current platform at runtime. Based on the OS, it renders platform-specific text, ensuring tailored user experience.

? Interactive Example

Simulate how Platform.select() applies different styles based on the OS. Switch between Android and iOS to see the Button style adapt:

Action Button
// Select a platform above to see the code logic...

? Use Cases

  • Different UI styles for Android and iOS
  • Platform-specific permissions
  • Using native APIs unique to a platform
  • Optimizing performance per OS

? Tips & Best Practices

  • Prefer shared code when possible
  • Use platform-specific files only when necessary
  • Keep platform logic simple and readable

?️ Try It Yourself

  1. Create a component that changes styles per platform
  2. Use Platform.select() for cleaner logic
  3. Experiment with .android.js and .ios.js files