Platform.OS
- React Native course
- Beginner
- Lesson 100/116
- 5 min
Learn OS detection with Platform.OS.
What is Platform.OS?
Your React Native app runs on both iOS and Android. Sometimes you need to know which platform you are on: for example you may want different padding on iOS and a different shadow style on Android. This information is provided by Platform.OS.
Platform.OS returns the string 'ios' or 'android'. You import Platform from the react-native package. By using it in a condition you can write platform-specific code: if (Platform.OS === 'ios').
Using Platform.OS
You use Platform.OS in an if condition to write platform-specific code. You can show one component on iOS and another on Android. Or you can give the same component different styles.
import { Platform, Text } from 'react-native';
if (Platform.OS === 'ios') {
return <Text>iOS device</Text>;
}
return <Text>Android device</Text>;The condition string is lowercase: 'ios' and 'android'. If you use uppercase it will not match. Always use === for comparison.
Practice Your turn: show text based on platform
Import Platform from react-native. If Platform.OS === 'ios' return <Text>iOS</Text>; otherwise return <Text>Android</Text>.
Starter code
import { Text } from 'react-native';
function Screen() {
// check the platform
return <Text>Device</Text>;
}Sample solution
import { Platform, Text } from 'react-native';
function Screen() {
if (Platform.OS === 'ios') {
return <Text>iOS</Text>;
}
return <Text>Android</Text>;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Platform.OS return?
Platform.OS- A number
- The string 'ios' or 'android' Correct answer
- A component
- An array
Explanation: Platform.OS returns the string 'ios' or 'android'.
2 Fill in the blank: Platform.OS check
if (Platform.____ === 'ios') { ... }
if (Platform.OS === 'ios') { ... }
Explanation: You check the platform with Platform.OS.
3 Match: value and platform
| Term | Meaning |
|---|---|
'ios' |
Apple devices |
'android' |
Google devices |
Platform.OS |
platform name |