Platform.select: Write Once, Adapt Anywhere
Platform.select is a switch statement for your UI, letting you apply styles or components for iOS and Android from one object. It's ideal for tweaking styles in StyleSheet.create or rendering different components. The footgun is forgetting a `default` key.
WHY IT EXISTS: React Native aims for "learn once, write anywhere," but iOS and Android have different design conventions, APIs, and user expectations. Hardcoding if (Platform.OS === 'ios') everywhere creates messy, hard-to-maintain code. A declarative approach was needed to isolate platform-specific logic.
THE MENTAL MODEL: Platform.select is a configuration map that returns the right value for the current operating system. You provide an object with keys for each platform (ios, android) and it picks the correct one at runtime. It's like telling your app, "Here are the blueprints for each platform; build the one you're on."
HOW IT WORKS: You pass an object to Platform.select. React Native checks the current platform against the object's keys in a specific order of precedence. First, it looks for a specific OS key like ios or android. If that's not found, it looks for a native key, which covers both ios and android. If that's also missing, it falls back to the default key. If no matching key is found and there's no default, it returns undefined, which can cause errors. The value for a key can be anything: a style object, a number, or even a function that returns a component.
WHEN TO USE IT: Use Platform.select for small-to-medium platform differences. It's perfect for adjusting padding, colors, or font sizes in a StyleSheet. It's also great for choosing which icon library to use or for returning a different component implementation when the logic differs significantly between platforms.
WHEN NOT TO USE IT: Don't use Platform.select for entire screens or complex logic flows. If you find yourself nesting Platform.select calls or putting large amounts of code inside, it's a sign that you should use platform-specific file extensions instead (e.g., MyComponent.ios.js and MyComponent.android.js). This approach keeps files cleaner and is better handled by the bundler.
ONE CANONICAL EXAMPLE: A common use is creating a container with different background colors. Inside StyleSheet.create, you can define a style like container: { flex: 1, ...Platform.select({ ios: { backgroundColor: 'red' }, android: { backgroundColor: 'green' }, default: { backgroundColor: 'blue' } }) }. This results in a red background on iOS, green on Android, and blue on any other platform like web. The spread operator (...) merges the platform-specific style object into the main style definition.
Read the original → reactnative.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.