0
0
React Nativemobile~5 mins

Platform-specific styles in React Native

Choose your learning style9 modes available
Introduction

Different devices may need different looks. Platform-specific styles help your app look right on each device.

You want a button to look different on iOS and Android.
You need to adjust font size or padding for each platform.
You want to use platform-specific colors or fonts.
You want to fix layout differences between iOS and Android.
You want to provide a native feel on each platform.
Syntax
React Native
import { Platform, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  container: {
    padding: Platform.OS === 'ios' ? 20 : 10,
    backgroundColor: Platform.select({
      ios: 'lightblue',
      android: 'lightgreen',
      default: 'white'
    })
  }
});

Platform.OS returns the current platform as a string ('ios' or 'android').

Platform.select() helps choose values for each platform easily.

Examples
Use a simple condition to set padding differently for iOS and Android.
React Native
padding: Platform.OS === 'ios' ? 20 : 10
Use Platform.select to pick colors for each platform.
React Native
backgroundColor: Platform.select({ ios: 'blue', android: 'green' })
Set font family depending on the platform.
React Native
fontFamily: Platform.OS === 'android' ? 'Roboto' : 'Arial'
Sample App

This app shows a centered text with background color and padding that change depending on the platform. The text color also changes.

React Native
import React from 'react';
import { View, Text, StyleSheet, Platform } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>Hello from {Platform.OS}!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: Platform.select({ ios: '#add8e6', android: '#90ee90', default: '#ffffff' }),
    padding: Platform.OS === 'ios' ? 30 : 15
  },
  text: {
    fontSize: 20,
    color: Platform.OS === 'ios' ? 'navy' : 'darkgreen'
  }
});
OutputSuccess
Important Notes

Always test your app on both iOS and Android devices or simulators to see platform-specific styles in action.

Use Platform.select for cleaner code when choosing multiple style values.

Remember to provide a default value in Platform.select for other platforms or web.

Summary

Platform-specific styles let your app look good on different devices.

Use Platform.OS or Platform.select to set styles conditionally.

Test on all platforms to ensure your styles work well everywhere.