0
0
React-nativeHow-ToBeginner ยท 4 min read

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 (row or column).
  • 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: 1 on container or children, causing layout to collapse.
  • Confusing justifyContent (main axis) with alignItems (cross axis).
  • Using unsupported values like flexDirection: 'left' instead of 'row' or 'column'.
  • Forgetting that default flexDirection is column, unlike web.
javascript
/* Wrong: flexDirection value */
const stylesWrong = {
  container: {
    flexDirection: 'left' // invalid value
  }
};

/* Right: valid flexDirection */
const stylesRight = {
  container: {
    flexDirection: 'row'
  }
};
๐Ÿ“Š

Quick Reference

PropertyDescriptionCommon Values
flexDirectionSets main axis direction'row', 'column'
justifyContentAligns children on main axis'flex-start', 'center', 'space-between', 'space-around'
alignItemsAligns children on cross axis'flex-start', 'center', 'stretch'
flexDefines how a child growsnumber (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.