Platform.select
- React Native course
- Beginner
- Lesson 101/116
- 5 min
Learn platform-specific styles with Platform.select.
Platform.select
Instead of writing if (Platform.OS === 'ios') every time you can use Platform.select. This function takes an object and returns the value for the current platform. It makes your code shorter and more readable.
const padding = Platform.select({
ios: 20,
android: 16,
});Here on iOS padding is 20, on Android 16. The object keys are ios and android. You can also provide a default key; it is used when no platform matches.
The Platform.select object
The object you pass to Platform.select has keys ios, android and an optional default. You can assign any value to each key: number, string, component, function. The value of the key matching the current platform is returned.
If the object has both ios and android, the value for whichever platform you are on is returned. default is used only when neither iOS nor Android key exists; for example on the web.
Practice Your turn: platform-specific padding
Import Platform. Assign padding to the result of Platform.select({ ios: 20, android: 16 }).
Starter code
import { Platform } from 'react-native';
// set padding with Platform.select
const padding = null;Sample solution
import { Platform } from 'react-native';
const padding = Platform.select({
ios: 20,
android: 16,
});Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: Platform.select call
const padding = Platform.____({ ios: 20, android: 16 });
const padding = Platform.select({ ios: 20, android: 16 });
Explanation: You get the platform-specific value with select.
2 What does Platform.select return?
Platform.select({ ios: 20, android: 16 })- An array
- All values
- The current platform's value Correct answer
- A function
Explanation: Platform.select returns the value for the current platform.
3 Match: key and usage
| Term | Meaning |
|---|---|
ios |
iOS value |
android |
Android value |
default |
fallback value |