Course contentsShow
← React Native
Lesson 107 of 1,5552. Project Scaffolding with ExpoFree lesson

Abstracting Platform-Specific Logic

Utilize platform-aware file extensions to cleanly separate iOS and Android implementations.

In this lesson, you will learn how to use platform-aware file extensions to keep your codebase clean while writing code that behaves differently on iOS and Android.

The Problem: Platform Bloat

As you build more complex features, you might find yourself writing "if-else" statements everywhere to check the operating system (e.g., if (Platform.OS === 'ios')). While this works, it quickly turns your components into unreadable nests of conditional logic.

The Solution: Platform-Aware Extensions

React Native’s Metro bundler has a powerful built-in feature: it automatically resolves files based on their extensions. Instead of putting platform logic inside one file, you can split the implementation into separate files.

If you have a component that needs to render a different visual style or use a different native module for each platform, you can create three files instead of one:

  1. MyComponent.ios.tsx (Contains only the iOS-specific logic)
  2. MyComponent.android.tsx (Contains only the Android-specific logic)
  3. MyComponent.tsx (Optional; for shared logic or as an entry point)

When you import this component in your main app file—like import MyComponent from './MyComponent';—Metro automatically detects the platform you are building for and bundles only the correct file. It essentially "snips out" the version that doesn't match your current target.

Example Illustration

Imagine you have a custom "CameraModule" that works differently on each platform:

  • CameraModule.ios.tsx:
    export const startCamera = () => console.log("Using iOS Camera Framework");
    
  • CameraModule.android.tsx:
    export const startCamera = () => console.log("Using Android Intent");
    

In your main screen, you simply call:

import { startCamera } from './CameraModule';

// No need to check Platform.OS!
startCamera();

By using this pattern, your main application logic remains clean, readable, and agnostic of the underlying operating system. You isolate the platform-specific "noise" into tiny, manageable files, making it much easier to test and maintain your code as the project scales.

Key Takeaway: Use the .ios.tsx and .android.tsx file suffixes to let the Metro bundler automatically handle platform-specific logic, keeping your primary component files clean and free of conditional checks.