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.
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.
// Import Platform API from react-native
import { Platform } from "react-native";
const osName = Platform.OS;
console.log(osName);
// 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>;
}
The component checks the current platform at runtime. Based on the OS, it renders platform-specific text, ensuring tailored user experience.
Simulate how Platform.select() applies different styles based on the OS. Switch between Android and iOS to see the Button style adapt:
Platform.select() for cleaner logic.android.js and .ios.js files