0
0
React Nativemobile~5 mins

Flexbox layout (flexDirection, justifyContent, alignItems) in React Native

Choose your learning style9 modes available
Introduction

Flexbox helps arrange items in a container easily. It makes layouts flexible and neat on different screen sizes.

You want to place buttons in a row or column evenly spaced.
You need to center text or images inside a box.
You want items to stretch or align nicely on different devices.
You want to create a navigation bar with items spaced apart.
You want to stack items vertically or horizontally with control.
Syntax
React Native
const styles = StyleSheet.create({
  container: {
    flexDirection: 'row', // or 'column'
    justifyContent: 'flex-start', // or 'center', 'flex-end', 'space-between', 'space-around', 'space-evenly'
    alignItems: 'flex-start' // or 'center', 'flex-end', 'stretch', 'baseline'
  }
});

flexDirection sets the main axis direction: 'row' means left to right, 'column' means top to bottom.

justifyContent aligns items along the main axis (horizontal if row, vertical if column).

Examples
Items are in a row, centered horizontally and vertically.
React Native
flexDirection: 'row'
justifyContent: 'center'
alignItems: 'center'
Items stack vertically with space between them, aligned to the left.
React Native
flexDirection: 'column'
justifyContent: 'space-between'
alignItems: 'flex-start'
Items in a row with equal space around, stretched vertically.
React Native
flexDirection: 'row'
justifyContent: 'space-around'
alignItems: 'stretch'
Sample App

This example shows three boxes arranged in a row. They have equal space around them and are centered vertically inside a light blue container.

React Native
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

export default function FlexboxExample() {
  return (
    <View style={styles.container} accessibilityLabel="Flexbox container">
      <Text style={styles.box} accessibilityLabel="Box 1">Box 1</Text>
      <Text style={styles.box} accessibilityLabel="Box 2">Box 2</Text>
      <Text style={styles.box} accessibilityLabel="Box 3">Box 3</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    height: 100,
    backgroundColor: '#e0f7fa',
    paddingHorizontal: 20
  },
  box: {
    backgroundColor: '#00796b',
    color: 'white',
    padding: 10,
    fontSize: 16,
    borderRadius: 5
  }
});
OutputSuccess
Important Notes

Use flexDirection to switch between horizontal and vertical layouts.

justifyContent controls spacing along the main axis, while alignItems controls alignment on the cross axis.

Accessibility labels help screen readers describe the layout and items.

Summary

Flexbox makes arranging items easy and flexible on any screen.

flexDirection sets the main layout direction.

justifyContent and alignItems control spacing and alignment.