Android – require a module specifically for iOS in React Native

androidiosreact-native

I am currently using react-native-safari-view module in my React Native project for showing web views in iOS.

As the module is not yet implemented for Android, when I try to build the project for Android, it gives me an error at this line:

import SafariView from 'react-native-safari-view'

I am going to use the Linking library for Android, but I don't know how to use the same code for two platforms.

I tried:

if (Platform.OS == 'ios') {
    import SafariView from 'react-native-safari-view'
}

And it gives me this error:

import' and 'export' may only appear at the top level

How do I get around this?

Best Answer

To get around this I have been using require instead (but mainly for modules rather than components):

var SafariView;

if (Platform.OS == 'ios') {
    SafariView = require('react-native-safari-view');
}

For this particular situation I would definitely go for Konstantin Kuznetsov's approach - Just sticking this here as it might help someone else where making a wrapper component with separate files may be overkill :)