Platform-Specific Code React Native
Platform-Specific Code React Native
Platform-Specific Code
When building a cross-platform app, you'll want to re-use as much code as possible.
Scenarios may arise where it makes sense for the code to be different, for example you
may want to implement separate visual components for Android and iOS.
React Native provides two ways to organize your code and separate it by platform:
Certain components may have properties that work on one platform only. All of these
props are annotated with @platform and have a small badge next to them on the
website.
Platform module
React Native provides a module that detects the platform in which the app is running.
You can use the detection logic to implement platform-specific code. Use this option
when only small parts of a component are platform-specific.
Platform.OS will be ios when running on iOS and android when running on Android.
There is also a Platform.select method available, that given an object where keys can
be one of 'ios' | 'android' | 'native' | 'default' , returns the most fitting value for
the platform you are currently running on. That is, if you're running on a phone, ios and
android keys will take preference. If those are not specified, native key will be used
and then the default key.
https://reactnative.dev/docs/platform-specific-code 1/4
28/2/24, 11:34 Platform-Specific Code · React Native
This will result in a container having flex: 1 on all platforms, a red background color on
iOS, a green background color on Android, and a blue background color on other
platforms.
Since it accepts any value, you can also use it to return platform-specific components,
like below:
<Component />;
<Component />;
On Android, the Platform module can also be used to detect the version of the Android
Platform in which the app is running:
Note: Version is set to the Android API version not the Android OS version. To find a
mapping please refer to Android Version History.
Platform-specific extensions
When your platform-specific code is more complex, you should consider splitting the
code out into separate files. React Native will detect when a file has a .ios. or
.android. extension and load the relevant platform file when required from other
components.
For example, say you have the following files in your project:
BigButton.ios.js
BigButton.android.js
https://reactnative.dev/docs/platform-specific-code 3/4
28/2/24, 11:34 Platform-Specific Code · React Native
React Native will automatically pick up the right file based on the running platform.
For example, say you have the following files in your project:
Pro tip: Configure your Web bundler to ignore .native.js extensions in order to avoid
having unused code in your production bundle, thus reducing the final bundle size.
https://reactnative.dev/docs/platform-specific-code 4/4