Layout with Flexbox
In React Native, element layout is done only with Flexbox, the same model as in CSS. There is no grid or float. If you know Flexbox from the web, you only need to remember a few differences.
Differences from the web
| Property | Web default | React Native default |
|---|---|---|
display | block | always flex |
flexDirection | row | column |
flexShrink | 1 | 0 |
alignContent | normal | flex-start |
The main point: every View is already a flex container, and elements go from top to bottom by default.
Filling the screen: flex 1
The root View of a screen usually gets flex: 1, meaning "take all free space":
// app/index.tsx
import { StyleSheet, Text, View } from 'react-native';
export default function Index() {
return (
<View style={styles.screen}>
<Text>My tasks</Text>
</View>
);
}
const styles = StyleSheet.create({
screen: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
});The white background fills the whole screen, and the text sits exactly in the center. Without flex: 1 the container would be as tall as the text, and justifyContent would move nothing.
A row: elements side by side
A task line needs a row: a checkmark on the left and the title next to it.
// components/TaskRow.tsx
import { StyleSheet, Text, View } from 'react-native';
export default function TaskRow({ title }: { title: string }) {
return (
<View style={styles.row}>
<View style={styles.check} />
<Text style={styles.title}>{title}</Text>
<Text>Delete</Text>
</View>
);
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
alignItems: 'center',
gap: 12,
padding: 12,
},
check: { width: 24, height: 24, borderWidth: 2, borderRadius: 12 },
title: { flex: 1, fontSize: 18 },
});Render <TaskRow title="Buy bread" /> in app/index.tsx. A circle appears on the left, then the title, and "Delete" is pushed to the right edge: flex: 1 on the title takes all the remaining width. gap sets the spacing between elements.
Main properties
| Property | What it does |
|---|---|
flexDirection | Direction: column or row |
justifyContent | Alignment along the direction |
alignItems | Alignment across the direction |
flex | Share of the free space |
flexWrap | Wrapping elements onto a new line |
gap | Spacing between elements |
Common mistake
Expecting justifyContent: 'space-between' to spread elements horizontally while forgetting flexDirection: 'row'. The default direction is a column, so the elements spread up and down. Set the direction first, then the alignment.