user6632504
user6632504

Reputation:

Can I require a module specifically for iOS in React 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?

Upvotes: 15

Views: 9894

Answers (3)

Hussam Kurd
Hussam Kurd

Reputation: 9196

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

You can then require the component as follows:

import BigButton from './BigButton'

reference https://facebook.github.io/react-native/docs/platform-specific-code.html#platform-specific-extensions

Upvotes: 10

David
David

Reputation: 7525

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 :)

Upvotes: 15

Konstantin Kuznetsov
Konstantin Kuznetsov

Reputation: 903

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

Upvotes: 5

Related Questions