Styling & Flexbox
How styling works
React Native doesn’t use CSS files. Instead you write styles as JavaScript objects, where properties are camelCase and most values are unitless numbers (density-independent pixels).
<View style={{ padding: 16, backgroundColor: '#f3eefe', borderRadius: 12 }}>
<Text style={{ fontSize: 18, fontWeight: 'bold', color: '#7c3aed' }}>Title</Text>
</View>
StyleSheet.create
For anything beyond a quick style, define styles with StyleSheet.create. It keeps your JSX clean and is slightly optimised.
import { StyleSheet, View, Text } from 'react-native';
function Card() {
return (
<View style={styles.card}>
<Text style={styles.title}>Profile</Text>
</View>
);
}
const styles = StyleSheet.create({
card: { padding: 16, backgroundColor: '#fff', borderRadius: 12 },
title: { fontSize: 18, fontWeight: 'bold' },
});
Combining and conditional styles
<View style={[styles.card, isActive && styles.active]} /> // array merges them
Flexbox: the layout system
React Native lays out everything with flexbox. One big difference from the web: the default flexDirection is column (top to bottom), not row. The key properties:
flexDirection—'column'(default) or'row'.justifyContent— spacing along the main axis.alignItems— alignment on the cross axis.flex: 1— grow to fill available space.
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 16 }}>
<Text>Left</Text>
<Text>Right</Text>
</View>
Filling the screen
<View style={{ flex: 1 }}> {/* fills the whole screen */}
<View style={{ flex: 1, backgroundColor: 'purple' }} /> {/* top half */}
<View style={{ flex: 1, backgroundColor: 'violet' }} /> {/* bottom half */}
</View>
Safe areas and responsiveness
Use SafeAreaView (or the safe-area-context library) to keep content clear of the notch and home indicator. For responsive sizes, use flex and percentages rather than fixed pixels.
Common mistakes
- Expecting
flexDirectionto default torow(it’scolumnhere). - Writing styles as CSS strings instead of objects.
- Hard-coding pixel sizes that break on different screens — prefer
flex.
Summary: Style with JS objects (camelCase) viaStyleSheet.create, and lay out with flexbox — remembering the default direction iscolumn. Useflex,justifyContentandalignItemsfor responsive layouts.