React Native: Write code depending on the plateforms

Introduction

React Native allows you to write code for the iOS and Android platforms using the Javascript and React syntaxes. With this logic, you will want to re-use as much code as possible for both platforms. However, at one point, you will have to write code for a specific platform. In this article, we will see how React native makes this possible.

The Platform module

First way to do this, the Platform module. You can import it like this:

import {Platform} from 'react-native'

Using this, we can now know which platform we are on with the Platform.OS.

<Text>{Platform.OS == 'ios' ? 'Hello IOS' : 'Hello Android'}</Text>

Platform.OS will return ‘ios’ or ‘android’. You can also use the select method:

<Text style={{
    color: 'blue',
    ...Platform.select({
        ios: {
            backgroundColor: 'red'
        },
        android: {
            backgroundColor: 'green'
        }
    })
}}>
    Hello World
</Text>

Our text will be blue on both platforms,but the background color will be red on iOS devices and green on Android.

The select method returns any value. You can give it whatever is valid with React:

const MyComponent = Platform.select({
    ios: () => <Text>Hello iOS</Text>,
    android: () => <Text>Hello Android</Text>
})

<MyComponent />

Get specific version

You can use Platform.Version to detect the iOS or Android version you are currently running on.

// On Android
const version = Platform.Version // 25 = 'Nougat'

// On iOS
const version = Platform.Version // 11.2.2

Using platform specific extensions

At one point, the Platform module may not be enough to write what you need and you might have to create entirely different components for iOS and Android. React Native is able to detect .ios or .android file extensions and load the correct component.

You can have files like this:


TopBar.ios.js TopBar.android.js

And import them like this:

import Topbar from './TopBar'

React Native will know which component to take thanks to the file extensions.

Have fun!!!

Your email address will not be published. Required fields are marked *

*