CodeBlanks Logo Icon CodeBlanks

Platform-specific components

Learn to write platform-specific components.

Platform-specific component

Platform.select can select not only numbers and strings but also components. When you want to show one component on iOS and another on Android you use this method. You assign a component to each key; Platform.select returns the one for the current platform.

const Button = Platform.select({
  ios: IOSButton,
  android: AndroidButton,
  default: DefaultButton,
});

Here the Button variable holds the relevant component on whichever platform you are on. You can use the component as <Button />; React Native renders the right one.

Practice Your turn: select component by platform

Import Platform. Assign Card to the result of Platform.select({ ios: IOSCard, android: AndroidCard, default: DefaultCard }).

Starter code

App.js
import { Platform } from 'react-native';

// set Card with Platform.select
const Card = null;

Sample solution

App.js
import { Platform } from 'react-native';

const Card = Platform.select({
  ios: IOSCard,
  android: AndroidCard,
  default: DefaultCard,
});

Default value

The default key in the Platform.select object is used when neither ios nor android key exists. This provides a safety net if your app is extended to a new platform (for example the web) in the future.

Usually you set the default value to the component of the platform you use most. For example if both iOS and Android values exist but there is no default, on the web undefined is returned and this causes an error. Adding default eliminates this risk.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: select component

Question
const Button = Platform.____({ ios: IOSButton, android: AndroidButton });
Answer
const Button = Platform.select({ ios: IOSButton, android: AndroidButton });

Explanation: You select the component with Platform.select.

2 How does selecting a component with Platform.select work?

App.js
Platform.select({ ios: A, android: B })
  • Returns the current platform's component Correct answer
  • Merges both components
  • Returns only the ios component
  • Throws an error

Explanation: Platform.select returns the current platform's component.

3 Match: key and usage

Term Meaning
ios iOS component
android Android component
default fallback component

All lessons in Beginner