Layout with Flexbox
Flexbox is the primary way to arrange elements in React Native. If you've used Flexbox in CSS, you already know most of what you need. The main difference is that Flexbox in React Native defaults to column direction instead of row. This makes sense because mobile screens are taller than they are wide.
Flexbox lets you control how elements are arranged, sized, and aligned within their container. It's incredibly powerful and you'll use it in almost every component you build.
Flex Direction
The flexDirection property controls the direction of the main axis. By default it's column (top to bottom), but you can change it to row (left to right).
import React from 'react';
import { View, StyleSheet } from 'react-native';
function FlexDemo() {
return (
<View style={styles.row}>
<View style={{ width: 50, height: 50, backgroundColor: 'red' }} />
<View style={{ width: 50, height: 50, backgroundColor: 'green' }} />
<View style={{ width: 50, height: 50, backgroundColor: 'blue' }} />
</View>
);
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
gap: 10,
},
});
export default FlexDemo;
With flexDirection: 'row', the three boxes appear side by side. With the default column, they'd stack vertically. The gap property adds spacing between items — it's the easiest way to space elements.
Justify Content and Align Items
These two properties control alignment. justifyContent aligns along the main axis, and alignItems aligns along the cross axis.
<View style={{
flex: 1,
justifyContent: 'center', // vertical centering (column direction)
alignItems: 'center', // horizontal centering
}}>
<View style={{ width: 100, height: 100, backgroundColor: 'red' }} />
</View>
The most common values for justifyContent are flex-start, center, flex-end, space-between, and space-around. For alignItems, you'll use flex-start, center, flex-end, and stretch. Combining these two properties gives you full control over where elements appear on screen.
Flex Grow and Shrink
The flex property controls how much space an element takes relative to its siblings. A flex value of 1 means the element expands to fill available space.
<View style={{ flexDirection: 'row', height: 200 }}>
<View style={{ flex: 1, backgroundColor: 'red' }} />
<View style={{ flex: 2, backgroundColor: 'blue' }} />
<View style={{ flex: 1, backgroundColor: 'green' }} />
</View>
The blue section takes twice as much space as the red and green sections because it has flex: 2 while they have flex: 1. This is how you create responsive layouts that adapt to different screen sizes — elements proportionally fill the available space.