At our company we have several React Native components built for iOS. They are all JavaScript based components, so they should work under React Native for Android also. Also, most of the components we have should only differ in the design style, so we need to code those differences between both platforms.
What's the right way to enable this components to support Android? Do we have to use if
's checking the app Platform
and change the style accordingly? If we want to separate the components in two files, Component.android.js
and Component.ios.js
, is React Native going to automatically detect which one it needs to use depending on the platform it's running?
There is a very simple solution which I prefer. Just use the file extension: .ios.
vs .android.
E.g. look at my nav. I use the android toolbar in the android nav and then I can use navigatorIos for ios if I wish. The application platform will correctly load the corresponding platform file just based on the extension. Which means I just load it normally:
var Nav = require('./jsx/Nav');
I like to follow a declarative approach that React talks about, thus:
1) organizing your files would be by function/behaviour and not by platform as the same file with different extensions will be next to each other.
2) Whether platform to be explicit or implicit isn't relevant as you will only split the file into extensions when it's different platform specific components (so this is inherent)
3) Never any need to handle different platform(s) behaviour in your code ever.
4) This is a composition solution as I've already mentioned: files that are cross-platform do not need the platform extension (and might not need an abstract class for extension in some cases even).
This is a simple solution and I do not know how well it would scale for large projects; but I'm all for the declarative simplicity about it.
I place my components into 3 directories:
/common/components/
/android/components/
/ios/components/
if
or switch
if
to retrieve the right style.<MyCameraWidget>
), then you might use a base <BaseCameraWidget>
and then have <CameraWidgetIOS>
and <CameraWidgetAndroid>
variants which extend the base component. This properly separates the cross-platform from the platform-specific logic for better component maintainability later on.
<CameraWidget>
facade which has the simple task of figuring out what plaform its on and rendering the correct <CameraWidgetIOS>
or <CameraWidgetAndroid>
component.Finally, read this Facebook article on adjustments you may want to make with the React Native packager. There is a blacklist feature which allows you to block out android or IOS files for different builds, but as of today that feature is undocumented and potentially not yet released.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With