React Native - Styling
React Native - Styling
Section titled “React Native - Styling”Styling in React Native is done using JavaScript. You don’t write CSS directly. Instead, you create JavaScript objects that mimic CSS properties. React Native uses a highly optimized implementation of Flexbox for layout.
While you can use inline styles by passing a JavaScript object directly to the style prop, the recommended approach for organization and performance is to use StyleSheet.create.
Using StyleSheet
Section titled “Using StyleSheet”StyleSheet.create allows you to define several styles in one place. It also helps by sending styles to the native side only once, potentially improving performance, and provides validation for style properties.
Style property names are typically camelCased, e.g., backgroundColor instead of background-color. Units like px are generally not used; numbers usually represent density-independent pixels.
Example Component:
App.js
<html> <body> <p>import React from 'react';import { StyleSheet, Text, View } from 'react-native';
const App = () => { const myName = 'React Native Developer';
return ( <View style={styles.container}> <Text style={styles.greetingText}> Hello, {myName}! </Text> <Text style={styles.descriptionText}> Welcome to learning styling in React Native. </Text> </View> );};
const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#f0f0f0', padding: 20, }, greetingText: { fontSize: 24, fontWeight: 'bold', color: 'dodgerblue', marginBottom: 10, // Margin between text elements textAlign: 'center', }, descriptionText: { fontSize: 16, color: 'dimgray', textAlign: 'center', },});
export default App; </p> </body></html>Output: This app will display a greeting message in a bold, dodger blue color, and a descriptive message below it in a dimgray color. Both texts will be centered within a light gray container that fills the screen.
Platform-Specific Styles
Section titled “Platform-Specific Styles”Sometimes, you might need to apply different styles for iOS and Android. React Native provides the Platform module for this:
<html> <body> <p>import { Platform, StyleSheet } from 'react-native';
const styles = StyleSheet.create({ textStyle: { color: Platform.OS === 'ios' ? 'green' : 'blue', fontSize: Platform.select({ ios: 20, android: 18, default: 16, // for other platforms like web }), },}); </p> </body></html>For more comprehensive information on styling, including lists of all available style props for different components, refer to the official React Native documentation on Style, Text Style Props, and View Style Props.