15

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?

3 Answers3

15

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

David
  • 7,395
  • 5
  • 29
  • 45
  • 8
    I had to add `.default` to the end of the import in my case. In this case it would be: `SafariView = require('react-native-safari-view').default;` – Chris Edwards Nov 02 '17 at 10:37
  • but I couldn't achieve this with var BackgroundTimer; if (Platform.OS == 'ios') { BackgroundTimer = require('react-native-background-timer').default; } error say... timeout is undefined when using .... const timeoutId = BackgroundTimer.setTimeout(() => { – Bikram Thapa Mar 03 '19 at 17:27
  • to help someone importing things which are not exported as default: let TouchableHighlight,TouchableOpacity; if (Platform.OS === 'ios') { ({ TouchableHighlight,TouchableOpacity } = require('react-native-gesture-handler')); } else { ({ TouchableHighlight,TouchableOpacity } = require('react-native')); } – Chenhua Aug 14 '20 at 06:45
10

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

Hussam Kurd
  • 8,066
  • 2
  • 43
  • 38
5

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.