0
0
React Nativemobile~20 mins

Flexbox layout (flexDirection, justifyContent, alignItems) in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Flexbox Layout Demo
This screen shows a row of colored boxes arranged using flexbox properties: flexDirection, justifyContent, and alignItems.
Target UI
-------------------------
| Flexbox Layout Demo   |
|-----------------------|
| [Red] [Green] [Blue]  |
|                       |
|                       |
-------------------------
Use a View container with flexDirection set to 'row'.
Inside the container, place three square Views colored red, green, and blue.
Use justifyContent to space the boxes evenly across the container.
Use alignItems to center the boxes vertically within the container.
Each colored box should be 60x60 pixels.
Starter Code
React Native
import React from 'react';
import { View, StyleSheet } from 'react-native';

export default function FlexboxLayoutDemo() {
  return (
    <View style={styles.container}>
      {/* TODO: Add three colored boxes here */}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    // TODO: Add flexDirection, justifyContent, alignItems
    padding: 20
  },
  box: {
    width: 60,
    height: 60
    // TODO: Add backgroundColor for each box
  }
});
Task 1
Task 2
Task 3
Task 4
Solution
React Native
import React from 'react';
import { View, StyleSheet } from 'react-native';

export default function FlexboxLayoutDemo() {
  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: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    padding: 20
  },
  box: {
    width: 60,
    height: 60
  }
});

We set the container's flexDirection to row so the boxes line up horizontally. justifyContent: 'space-around' spreads the boxes evenly with space around them. alignItems: 'center' centers the boxes vertically inside the container. Each box is a square 60x60 with a different background color: red, green, and blue.

This layout uses flexbox properties to control direction and spacing, which is very common in React Native for arranging UI elements.

Final Result
Completed Screen
-------------------------
| Flexbox Layout Demo   |
|-----------------------|
|  [Red]   [Green]  [Blue]  |
|                       |
|                       |
-------------------------
The three colored boxes appear in a horizontal row.
Boxes are spaced evenly with space around them.
Boxes are vertically centered in the screen.
Stretch Goal
Add a toggle button to switch flexDirection between 'row' and 'column'.
💡 Hint
Use React useState to track flexDirection and update container style dynamically.