Can I require a module specifically for iOS in React Native?

I am currently using the react-native-safari-view module in my React Native project to display web views in iOS.

Since the module is not yet implemented for Android, when I try to create a project for Android, it gives me an error in this line:

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

I am going to use the Linking library for Android, but I do not know how to use the same code for two platforms.

I tried:

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

And this gives me this error:

import 'and' export 'can only be displayed at the top level

How do I get around this?

+7
android ios react-native
source share
3 answers

To get around this, I used instead of require (but mainly for modules, not components):

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

In this particular situation, I would definitely go for Konstantin Kuznetsov's approach - just stick with it here, as this may help someone where creating a wrapper component with separate files can be excessive :)

+4
source share

You can split the platform code by creating two different files your_file_name.android.js and your_file_name.ios.js . Thus, you can create two versions for the file in which you want to use SafariView , or create a wrapper around SafariView that will export this module on iOS and a dummy object on Android, and then use this shell with Platform.OS tags.

+3
source share

platform-specific code is more complex, you should consider splitting code into separate files. React Native will detect when a file has .ios. or .android. expand and download the appropriate platform file, if required from other components.

For example, say that your project has the following files:

 BigButton.ios.js BigButton.android.js 

Then you can require the component as follows:

 import BigButton from './BigButton' 

link https://facebook.imtqy.com/react-native/docs/platform-specific-code.html#platform-specific-extensions

+3
source share

All Articles