How to Use Flexbox in React Native for Layouts
In React Native, use
flexbox by applying style properties like flexDirection, justifyContent, and alignItems to View components. These control layout direction, alignment, and spacing to build flexible UI layouts easily.Syntax
Flexbox in React Native uses style properties on View components to control layout. Key properties include:
flexDirection: sets layout direction (roworcolumn).justifyContent: aligns children along the main axis.alignItems: aligns children along the cross axis.flex: defines how a child grows to fill space.
javascript
const styles = StyleSheet.create({ container: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', flex: 1 } });
Example
This example shows a horizontal row with three colored boxes spaced evenly and centered vertically.
javascript
import React from 'react'; import { View, StyleSheet } from 'react-native'; export default function App() { return ( <View style={styles.container}> <View style={[styles.box, {backgroundColor: 'red'}]} /> <View style={[styles.box, {backgroundColor: 'green'}]} /> <View style={[styles.box, {backgroundColor: 'blue'}]} /> </View> ); } const styles = StyleSheet.create({ container: { flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center', flex: 1 }, box: { width: 50, height: 50 } });
Output
A full screen horizontal row with three squares colored red, green, and blue spaced evenly and vertically centered.
Common Pitfalls
Common mistakes when using flexbox in React Native include:
- Not setting
flex: 1on container or children, causing layout to collapse. - Confusing
justifyContent(main axis) withalignItems(cross axis). - Using unsupported values like
flexDirection: 'left'instead of'row'or'column'. - Forgetting that default
flexDirectioniscolumn, unlike web.
javascript
/* Wrong: flexDirection value */ const stylesWrong = { container: { flexDirection: 'left' // invalid value } }; /* Right: valid flexDirection */ const stylesRight = { container: { flexDirection: 'row' } };
Quick Reference
| Property | Description | Common Values |
|---|---|---|
| flexDirection | Sets main axis direction | 'row', 'column' |
| justifyContent | Aligns children on main axis | 'flex-start', 'center', 'space-between', 'space-around' |
| alignItems | Aligns children on cross axis | 'flex-start', 'center', 'stretch' |
| flex | Defines how a child grows | number (e.g., 1, 2) |
Key Takeaways
Use
flexDirection to set layout direction: 'row' or 'column'.Control spacing with
justifyContent and alignment with alignItems.Set
flex: 1 on containers or children to fill available space.Remember React Native defaults to
flexDirection: 'column', unlike web.Avoid invalid values and understand main vs cross axis to prevent layout bugs.