In this lesson, you will learn how to write cleaner, more maintainable code by splitting component logic into separate files for iOS and Android using platform-specific extensions.
Why use file extensions?
When building cross-platform apps, you often run into situations where a component needs to look or behave differently depending on the operating system. While we previously learned how to use the Platform module to write "if/else" logic inside a single file, this can quickly become messy as your components grow.
React Native provides a cleaner solution: if you name your files with .ios.js or .android.js suffixes, the packager will automatically pick the file that matches the platform you are building for.
How it works
Imagine you are building a custom Button component. Instead of putting both iOS and Android logic in one file, you can create three files in your folder:
CustomButton.ios.jsCustomButton.android.jsCustomButton.js(a fallback or shared entry point)
When you import the component in your app using import CustomButton from './CustomButton', React Native looks at the current platform. If you are running the app on an iPhone, it will automatically pull the code from CustomButton.ios.js. If you are on Android, it grabs CustomButton.android.js.
Example
In CustomButton.ios.js, you might include iOS-specific styling like ShadowProps for a blur effect, while in CustomButton.android.js, you might implement an elevation property for a Material Design look:
// CustomButton.ios.js
export const CustomButton = () => <View style={{ shadowOpacity: 0.5 }} />;
// CustomButton.android.js
export const CustomButton = () => <View style={{ elevation: 5 }} />;
This approach keeps your codebase organized because you no longer need to clutter your component with platform-checking logic. Your imports remain simple, and your component files remain focused on a single platform's design language, making them much easier to read and test.
Key Takeaway: By using .ios.js and .android.js file extensions, React Native automatically handles platform-specific code loading, allowing you to build cleaner, more modular components.