Styling & Flexbox
React Native styles look like CSS-in-JS objects, but they’re a flexbox-only subset. Layout is flexbox; values are unit-less density-independent pixels (dp); colours and shadows differ between iOS and Android.
StyleSheet, flexbox, platform tweaks
EXAMPLE
import { StyleSheet, View, Text, Platform, Pressable, useWindowDimensions } from 'react-native';
// 1) StyleSheet.create — validated + interned
const styles = StyleSheet.create({
screen: {
flex: 1,
backgroundColor: '#0f172a',
paddingHorizontal: 16,
paddingTop: 56,
},
title: {
fontSize: 24,
fontWeight: '600',
color: 'white',
},
row: {
flexDirection: 'row',
alignItems: 'center',
gap: 12, // RN 0.71+, like CSS gap
},
card: {
flex: 1,
backgroundColor: '#1e293b',
borderRadius: 12,
padding: 16,
// Shadows differ per platform
...Platform.select({
ios: {
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.2,
shadowRadius: 6,
},
android: {
elevation: 4,
},
}),
},
});
// 2) Compose styles — pass an array
<View style={[styles.row, { marginTop: 12 }]}>
<Text style={styles.title}>Hello</Text>
</View>
// 3) Conditional styles
<View style={[styles.card, isActive && { borderColor: '#0ea5e9', borderWidth: 2 }]} />
// 4) Responsive — useWindowDimensions hook
function Layout() {
const { width } = useWindowDimensions();
const isTablet = width >= 768;
return <View style={isTablet ? styles.rowTablet : styles.colPhone}>…</View>;
}
// 5) Pressable — interactive style based on state
<Pressable
style={({ pressed }) => [
styles.button,
pressed && { opacity: 0.7 },
]}
>
<Text style={styles.buttonLabel}>Save</Text>
</Pressable>
// 6) Tailwind-style — NativeWind (a popular choice)
// npm i nativewind
// <View className="flex-1 bg-slate-900 px-4 pt-14">…</View>
// 7) Common pitfalls
// • No width/height units — they're DP, never write '12px'
// • Borders inside borderRadius can show seams — set overflow: 'hidden'
// • Margins don't collapse — total spacing is the sum on both sides
Why it matters
Use gap (RN 0.71+) over marginRight on row items. It saves you the “last-child no-margin” dance and matches the web’s CSS gap exactly.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
// Flexbox is the layout system. Default flexDirection is 'column'.
<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
<Text>left</Text><Text>right</Text>
</View>
Try it Yourself »
Exercise
Default layout system.
// React Native uses
for layout.
Seven letters.
Discussion
Loading…