Understanding Flexbox Layout in React Native – Detailed Notes
Course: React Native Training
Topic: Understanding Flexbox Layout
Course Link: React Native Training Course
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to Flexbox Layout
Flexbox is a layout system used in React Native to arrange components, distribute available space, and control the alignment of elements within a parent container. It helps developers create flexible and responsive interfaces for mobile applications.
In React Native, Flexbox is commonly used to position headings, buttons, images, cards, navigation bars, profile sections, forms, and other interface elements. Instead of manually positioning every component, developers can use Flexbox properties to control how children are arranged within their parent.
Flexbox is particularly useful because mobile applications run on devices with different screen dimensions, orientations, and resolutions. A properly designed Flexbox layout can adapt to available space without requiring every element to have a fixed position.
Example
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.item}>First Item</Text>
<Text style={styles.item}>Second Item</Text>
<Text style={styles.item}>Third Item</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
item: {
padding: 15,
margin: 5,
backgroundColor: '#DBEAFE',
color: '#1E3A8A',
},
});
In this example, the parent container uses Flexbox to arrange three text elements vertically and center them within the available space.
2. Learning Objectives
After completing this topic, learners should be able to:
- Understand the purpose of Flexbox in React Native.
- Identify the main axis and cross axis.
- Use the
flexDirection property to arrange components.
- Control spacing with
justifyContent.
- Align children with
alignItems and alignSelf.
- Understand how
flex, flexGrow, and flexShrink work.
- Use
flexWrap and alignContent for multi-line layouts.
- Create rows, columns, cards, and screen layouts.
- Build responsive interfaces using flexible dimensions.
- Identify and fix common Flexbox layout problems.
3. What Is Flexbox?
Flexbox, short for Flexible Box Layout, is a layout model that distributes space among child components and controls their alignment within a container.
In React Native, a component such as View can act as a Flexbox container. Its child components are arranged according to the styles defined on the parent and, when necessary, on the children themselves.
Important Characteristics
- Arranges children horizontally or vertically.
- Supports alignment along two axes.
- Distributes available space between child components.
- Allows children to grow or shrink according to layout rules.
- Supports wrapping items onto multiple lines.
- Helps create layouts that adapt to available screen space.
Basic Flexbox Structure
<View style={styles.container}>
<View style={styles.boxOne} />
<View style={styles.boxTwo} />
<View style={styles.boxThree} />
</View>
The outer View is the Flexbox container, while the three inner View elements are its children, also called flex items.
4. Flexbox Defaults in React Native
React Native uses Flexbox concepts similar to CSS, but some defaults are different. Understanding these differences helps prevent unexpected layouts.
| Property or Behavior |
React Native Default |
Explanation |
flexDirection |
column |
Children are arranged vertically by default. |
justifyContent |
flex-start |
Children begin at the start of the main axis. |
alignItems |
stretch |
Children can stretch along the cross axis when their dimensions allow it. |
flexWrap |
nowrap |
Children remain on one line unless wrapping is enabled. |
flexShrink |
0 |
Children do not shrink by default in the same way they do in web CSS. |
These defaults differ from common web CSS defaults. When a layout does not behave as expected, explicitly setting the relevant Flexbox properties can make the intended arrangement easier to understand.
5. Understanding the Flexbox Container and Children
A Flexbox layout has a parent container and one or more child components. The parent determines the primary arrangement and alignment rules, while individual children can define their own dimensions and flex behavior.
Parent Container
The parent usually defines properties such as flexDirection, justifyContent, alignItems, flexWrap, and gap.
Child Components
Children can define properties such as flex, flexGrow, flexShrink, flexBasis, alignSelf, and dimensions.
Example
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
padding: 16,
},
item: {
width: 80,
height: 80,
backgroundColor: '#BFDBFE',
},
});
Here, the parent arranges children horizontally, distributes available space between them, and aligns them along the cross axis.
6. Main Axis and Cross Axis
The main axis and cross axis are fundamental concepts in Flexbox. They determine the direction in which components are arranged and the direction in which they are aligned.
Main Axis
The main axis follows the direction specified by flexDirection. If the direction is row, the main axis is horizontal. If it is column, the main axis is vertical.
Cross Axis
The cross axis is perpendicular to the main axis. When the main axis is horizontal, the cross axis is vertical. When the main axis is vertical, the cross axis is horizontal.
| flexDirection |
Main Axis |
Cross Axis |
row |
Horizontal |
Vertical |
row-reverse |
Horizontal, reversed order |
Vertical |
column |
Vertical |
Horizontal |
column-reverse |
Vertical, reversed order |
Horizontal |
Important: justifyContent aligns children along the main axis, while alignItems aligns children along the cross axis.
7. Understanding flexDirection
The flexDirection property determines the direction in which children are laid out within a Flexbox container.
Available Values
column: Arranges children from top to bottom. This is the default in React Native.
row: Arranges children horizontally.
column-reverse: Arranges children from bottom to top.
row-reverse: Arranges children in the reverse horizontal direction.
Example: Row Layout
import React from 'react';
import { View, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<View style={styles.boxOne} />
<View style={styles.boxTwo} />
<View style={styles.boxThree} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
boxOne: {
width: 60,
height: 60,
backgroundColor: '#60A5FA',
},
boxTwo: {
width: 60,
height: 60,
backgroundColor: '#34D399',
},
boxThree: {
width: 60,
height: 60,
backgroundColor: '#FBBF24',
},
});
The three boxes appear in a horizontal row and are centered along the container's main axis and cross axis.
Example: Column Layout
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}
This arrangement places the children vertically and centers them within the parent.
8. Understanding justifyContent
The justifyContent property controls how child components are distributed along the main axis of a Flexbox container.
Common Values
| Value |
Description |
Typical Use |
flex-start |
Places children at the start of the main axis. |
Default stacking or grouping. |
flex-end |
Places children at the end of the main axis. |
Aligning controls toward an edge. |
center |
Centers children along the main axis. |
Centered content. |
space-between |
Places the first and last children at opposite ends and distributes remaining space between children. |
Header and footer arrangements. |
space-around |
Distributes space around each child. |
Spaced groups of items. |
space-evenly |
Distributes equal spacing between children and the container edges. |
Evenly spaced controls. |
Example
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
padding: 20,
},
box: {
width: 50,
height: 50,
backgroundColor: '#93C5FD',
},
});
When three boxes are placed inside this container, the first box sits near the start, the last box sits near the end, and the remaining available space is distributed between the boxes.
9. Understanding alignItems
The alignItems property controls the alignment of children along the cross axis. Its visual effect depends on the container's flexDirection.
Common Values
flex-start: Aligns children at the start of the cross axis.
flex-end: Aligns children at the end of the cross axis.
center: Centers children along the cross axis.
stretch: Stretches children along the cross axis when their dimensions allow it.
baseline: Aligns children according to their text baseline where applicable.
Example
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
box: {
width: 70,
height: 70,
margin: 5,
backgroundColor: '#A7F3D0',
},
});
In this row layout, alignItems: 'center' centers the boxes vertically within the available cross-axis space.
Remember that alignItems: 'stretch' will not visibly stretch a child along an axis if that child already has a fixed dimension on that axis.
10. Understanding alignSelf
The alignSelf property allows one child to override the cross-axis alignment specified by its parent. It is useful when most children should follow the same alignment but one child needs different positioning.
Example
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
padding: 20,
},
firstBox: {
width: 100,
height: 60,
backgroundColor: '#BFDBFE',
},
secondBox: {
width: 100,
height: 60,
backgroundColor: '#A7F3D0',
alignSelf: 'flex-start',
},
thirdBox: {
width: 100,
height: 60,
backgroundColor: '#FDE68A',
},
});
The parent centers its children by default, but the second box moves to the start of the cross axis because it uses alignSelf: 'flex-start'.
11. Understanding flex
The flex property controls how a component uses available space along the main axis of its parent. It is frequently used to create flexible columns, equal-width panels, and layouts that fill the screen.
In React Native, positive numeric flex values are commonly used to distribute available space among sibling components. The result depends on the parent dimensions, the children's other layout properties, and the space available.
Example
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
first: {
flex: 1,
backgroundColor: '#60A5FA',
},
second: {
flex: 2,
backgroundColor: '#34D399',
},
third: {
flex: 3,
backgroundColor: '#FBBF24',
},
});
If the three children share the available space and no other constraints interfere, their flexible portions are in the ratio 1:2:3.
| Child |
Flex Value |
Approximate Share of Flexible Space |
| First |
1 |
One-sixth |
| Second |
2 |
Two-sixths |
| Third |
3 |
Three-sixths |
This ratio describes the distribution of flexible space, not necessarily the final physical dimensions in every layout. Fixed dimensions, padding, margins, and constraints can affect the result.
12. Understanding flexGrow
The flexGrow property determines how remaining space along the main axis is distributed among children after their initial sizes have been considered.
flexGrow: 0 means the child does not grow to consume extra space through flex growth.
flexGrow: 1 allows the child to receive a proportional share of remaining space.
flexGrow: 2 gives the child twice the growth share of a sibling with flexGrow: 1, assuming comparable layout conditions.
Example
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
flex: 1,
},
small: {
width: 60,
flexGrow: 0,
backgroundColor: '#93C5FD',
},
expanding: {
flexGrow: 1,
backgroundColor: '#86EFAC',
},
});
The first child has a specified width and does not grow through flexGrow. The second child can use the remaining available space.
13. Understanding flexShrink
The flexShrink property controls how children shrink along the main axis when their combined size exceeds the space available in the container.
flexShrink: 0: The child does not shrink through this property.
flexShrink: 1: The child can shrink when necessary.
- Higher values indicate a greater proportional shrink factor under comparable conditions.
In React Native, flexShrink defaults to 0, unlike the common web CSS default of 1. This distinction can be important when a row contains long text or several fixed-width elements.
Example
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
},
label: {
width: 120,
flexShrink: 0,
},
description: {
flexShrink: 1,
},
});
Here, the label keeps its width, while the description can shrink to fit the remaining space. For long text, you may also need to consider text wrapping and the available width.
14. Understanding flexBasis
The flexBasis property defines the initial size of a flex item along the main axis before flexible growth or shrink calculations are applied.
- In a row layout,
flexBasis influences the initial width.
- In a column layout,
flexBasis influences the initial height.
- It can be used to define a starting size while allowing the layout to adapt.
Example
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
item: {
flexBasis: 120,
flexGrow: 1,
backgroundColor: '#BFDBFE',
margin: 4,
},
});
Each item starts with a basis of 120 layout units and can grow to use available space. The final dimensions depend on the number of items and the container's available width.
15. Understanding flexWrap
The flexWrap property determines whether children can move onto multiple lines when they no longer fit on a single line along the main axis.
Available Values
nowrap: Keeps children on one line. This is the default.
wrap: Allows children to continue on additional lines.
wrap-reverse: Allows wrapping in the reverse cross-axis direction where supported.
Example
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'flex-start',
gap: 10,
padding: 12,
},
item: {
width: 100,
height: 80,
backgroundColor: '#BFDBFE',
},
});
When the available width is insufficient for all items on one line, the items can wrap to additional rows. This is useful for tags, categories, small cards, and button groups.
16. Understanding alignContent
The alignContent property controls how multiple wrapped lines are distributed along the cross axis. It is relevant when a Flexbox container has multiple lines, typically because flexWrap: 'wrap' is enabled.
Common Values
flex-start: Groups lines at the start of the cross axis.
flex-end: Groups lines at the end of the cross axis.
center: Centers the lines.
space-between: Distributes remaining space between lines.
space-around: Distributes space around lines.
space-evenly: Distributes equal spacing between lines and container edges.
stretch: Stretches lines where space and layout conditions allow it.
Example
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
alignContent: 'space-between',
padding: 12,
},
item: {
width: 90,
height: 60,
margin: 4,
backgroundColor: '#A7F3D0',
},
});
Remember the difference: alignItems aligns individual children on the cross axis, while alignContent distributes multiple lines of children.
17. Using gap, rowGap, and columnGap
The gap properties define spacing between flex items without requiring individual margins on every child. Support depends on the React Native version and project configuration.
gap: Sets the spacing between rows and columns.
rowGap: Sets spacing between rows.
columnGap: Sets spacing between columns.
Example
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 12,
padding: 16,
},
card: {
width: 140,
padding: 12,
backgroundColor: '#DBEAFE',
borderRadius: 8,
},
});
Using a gap can make spacing consistent and easier to maintain. If the project uses a React Native version without the required support, use appropriate margins or another supported layout approach.
18. Using Flexbox to Center Components
Centering is one of the most common Flexbox tasks. To center a child both horizontally and vertically within a parent, set justifyContent: 'center' and alignItems: 'center' on the parent.
Example
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<View style={styles.card}>
<Text style={styles.text}>Centered Content</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
card: {
padding: 24,
backgroundColor: '#DBEAFE',
borderRadius: 12,
},
text: {
fontSize: 18,
fontWeight: 'bold',
},
});
Because the default direction is column, the main axis is vertical in this example. Therefore, justifyContent centers vertically and alignItems centers horizontally.
19. Creating a Header with Flexbox
Flexbox can arrange a screen header with a title on one side and an action button on the other. The row direction is commonly used for this layout.
Example
import React from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.header}>
<Text style={styles.title}>Dashboard</Text>
<Pressable onPress={() => console.log('Settings pressed')}>
<Text style={styles.action}>Settings</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
padding: 16,
backgroundColor: '#FFFFFF',
},
title: {
fontSize: 22,
fontWeight: 'bold',
color: '#111827',
},
action: {
fontSize: 15,
color: '#2563EB',
},
});
The title and settings action are positioned on opposite sides of the header, and alignItems: 'center' aligns them vertically.
20. Creating a Two-Column Layout
A two-column layout is useful for dashboards, product listings, profile information, and settings screens. It can be created by using a row container and giving its children flexible widths.
Example
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<View style={styles.column}>
<Text>Column One</Text>
</View>
<View style={styles.column}>
<Text>Column Two</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
gap: 12,
padding: 16,
},
column: {
flex: 1,
padding: 16,
backgroundColor: '#DBEAFE',
borderRadius: 8,
},
});
Both columns use flex: 1, so they share the available flexible space equally, subject to the container's padding and gap.
21. Creating a Screen with Header, Content, and Footer
A common mobile layout contains a header at the top, a flexible content section in the middle, and a footer at the bottom. Flexbox makes it possible to keep the footer near the bottom while allowing the content area to use the remaining space.
Example
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.screen}>
<View style={styles.header}>
<Text style={styles.headerText}>My Application</Text>
</View>
<View style={styles.content}>
<Text>Main Content Area</Text>
</View>
<View style={styles.footer}>
<Text>Footer Navigation</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: {
flex: 1,
},
header: {
height: 70,
justifyContent: 'center',
paddingHorizontal: 16,
backgroundColor: '#BFDBFE',
},
headerText: {
fontSize: 20,
fontWeight: 'bold',
},
content: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 16,
backgroundColor: '#F3F4F6',
},
footer: {
minHeight: 60,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#A7F3D0',
},
});
The screen container fills the available space. The header and footer use their own dimensions, while the content area expands to fill the remaining space.
22. Responsive Layouts with Flexbox
Responsive layouts adapt to different screen sizes and available space. Flexbox helps create responsive interfaces by distributing space based on the parent dimensions and the properties of its children.
Recommended Techniques
- Use flexible dimensions when possible.
- Use
flex: 1 for content that should occupy remaining space.
- Avoid unnecessary fixed widths for large layout sections.
- Use
flexWrap: 'wrap' when items should continue onto additional rows.
- Test the layout on different screen sizes and orientations.
- Check long text, larger accessibility fonts, and narrow screens.
- Use
useWindowDimensions() if the design needs to respond to changing window dimensions.
Example
import React from 'react';
import { View, Text, StyleSheet, useWindowDimensions } from 'react-native';
export default function App() {
const { width } = useWindowDimensions();
const isCompact = width < 400;
return (
<View style={[
styles.container,
isCompact ? styles.compact : styles.wide
]}>
<Text style={styles.text}>Responsive Flexbox Layout</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 16,
},
compact: {
flexDirection: 'column',
},
wide: {
flexDirection: 'row',
alignItems: 'center',
},
text: {
fontSize: 18,
color: '#1F2937',
},
});
This example changes the layout direction based on window width. The threshold is illustrative and should be chosen according to the needs of the actual interface.
23. Flexbox with Cards and Lists
Cards and list items frequently use Flexbox to arrange text, images, and action buttons. For example, a product row can display an image on the left, descriptive text in the center, and a price on the right.
Example
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function ProductRow() {
return (
<View style={styles.row}>
<View style={styles.imagePlaceholder} />
<View style={styles.details}>
<Text style={styles.name}>Wireless Headphones</Text>
<Text style={styles.description}>Comfortable everyday audio</Text>
</View>
<Text style={styles.price}>$49</Text>
</View>
);
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
alignItems: 'center',
padding: 12,
gap: 12,
backgroundColor: '#FFFFFF',
},
imagePlaceholder: {
width: 64,
height: 64,
borderRadius: 8,
backgroundColor: '#DBEAFE',
},
details: {
flex: 1,
},
name: {
fontSize: 16,
fontWeight: 'bold',
},
description: {
marginTop: 4,
color: '#6B7280',
},
price: {
fontSize: 16,
fontWeight: 'bold',
},
});
The details section uses flex: 1 to consume the space between the image and price. This lets the row adapt more easily to the available width.
24. Flexbox and Absolute Positioning
Flexbox is suitable for arranging components in the normal layout flow. Absolute positioning is useful for placing one element over another, such as a badge on a card or an icon in a corner.
Example
const styles = StyleSheet.create({
card: {
position: 'relative',
padding: 20,
minHeight: 140,
backgroundColor: '#DBEAFE',
borderRadius: 12,
},
badge: {
position: 'absolute',
top: 8,
right: 8,
paddingHorizontal: 8,
paddingVertical: 4,
backgroundColor: '#2563EB',
borderRadius: 6,
},
});
The card uses normal layout properties, while the badge is positioned independently within the relevant containing block. Use absolute positioning for overlays rather than as a replacement for every layout relationship.
25. Layout Direction and Right-to-Left Support
React Native supports left-to-right (LTR) and right-to-left (RTL) layout directions. This is important when building applications for languages that read from right to left.
- LTR: The default layout direction in many applications, where the start edge is the left side.
- RTL: Reverses the meaning of start and end edges for layout direction and supports right-to-left interfaces.
- Start and end properties: Prefer logical properties such as
marginStart and paddingEnd when they are more appropriate than fixed left and right spacing.
Test RTL layouts with the application's supported language configuration. Do not assume that changing the text alignment alone is enough to create a complete RTL layout.
26. Common Flexbox Layout Mistakes
| Mistake |
Possible Cause |
Solution |
| Children appear vertically instead of horizontally. |
The default direction is column. |
Set flexDirection: 'row'. |
| Content is not centered. |
The main and cross axes are misunderstood. |
Check the direction and use both justifyContent and alignItems as needed. |
| Flex children are invisible. |
The parent may have no available size. |
Give the parent a size or suitable flex value. |
| Text or children overflow. |
Children may not shrink or wrap as expected. |
Check widths, flexShrink, text wrapping, and available space. |
| Items do not wrap onto new lines. |
flexWrap remains set to nowrap. |
Set flexWrap: 'wrap'. |
| Wrapped rows are not spaced as expected. |
alignContent is missing or the container has no extra space. |
Review container dimensions and line alignment. |
| Children stretch unexpectedly. |
alignItems: 'stretch' is applied. |
Set an appropriate alignment or explicit child dimensions. |
| Gap has no effect. |
The React Native version or project setup may not support the property. |
Check version support or use margins. |
| Layout works on one device only. |
Fixed dimensions or assumptions about screen size. |
Use flexible sizing and test different dimensions. |
27. Debugging Flexbox Layouts
When a layout behaves unexpectedly, inspect the parent and children rather than changing random properties. Flexbox alignment always depends on the container's direction, dimensions, and available space.
Debugging Steps
- Identify the parent container and its child components.
- Check the parent's
flexDirection.
- Identify the main axis and cross axis.
- Review
justifyContent and alignItems.
- Inspect fixed dimensions, margins, padding, and gaps.
- Check
flex, flexGrow, flexShrink, and flexBasis.
- Temporarily add background colors to identify the boundaries of components.
- Use React Native DevTools or the available layout inspector.
- Test on the intended platforms and screen sizes.
Example: Fixing a Component That Does Not Fill the Screen
const styles = StyleSheet.create({
screen: {
flex: 1,
},
content: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
Both the screen and content containers are configured to use available space. However, the parent of the screen must itself receive a meaningful size for this layout to work as intended.
28. Flexbox Best Practices
- Understand the main axis before adjusting alignment properties.
- Use
flexDirection explicitly when the layout direction is important.
- Use
justifyContent for main-axis distribution.
- Use
alignItems for cross-axis alignment of children.
- Use
alignSelf when one child needs different alignment.
- Use
flex: 1 for flexible sections that should use remaining space.
- Use
flexGrow and flexShrink when you need more explicit control.
- Use
flexWrap for groups that need multiple rows.
- Use
gap where supported to maintain consistent spacing.
- Avoid excessive fixed dimensions in responsive sections.
- Consider long text and accessibility font scaling.
- Test layouts on Android and iOS if both platforms are supported.
29. Practical Project: Build a Flexbox Dashboard
In this project, you will create a simple dashboard containing a header, three summary cards, a flexible content section, and a footer. This project demonstrates row and column layouts, spacing, alignment, and flexible dimensions.
Complete Project Code
import React from 'react';
import { View, Text, StyleSheet, ScrollView } from 'react-native';
export default function App() {
return (
<View style={styles.screen}>
<View style={styles.header}>
<Text style={styles.headerTitle}>My Dashboard</Text>
<Text style={styles.headerSubtitle}>Overview</Text>
</View>
<ScrollView contentContainerStyle={styles.scrollContent}>
<View style={styles.cards}>
<View style={[styles.card, styles.blueCard]}>
<Text style={styles.cardLabel}>Users</Text>
<Text style={styles.cardValue}>120</Text>
</View>
<View style={[styles.card, styles.greenCard]}>
<Text style={styles.cardLabel}>Orders</Text>
<Text style={styles.cardValue}>85</Text>
</View>
<View style={[styles.card, styles.orangeCard]}>
<Text style={styles.cardLabel}>Revenue</Text>
<Text style={styles.cardValue}>$950</Text>
</View>
</View>
<View style={styles.contentPanel}>
<Text style={styles.panelTitle}>Recent Activity</Text>
<Text style={styles.panelText}>
Your recent updates and reports appear here.
</Text>
</View>
</ScrollView>
<View style={styles.footer}>
<Text style={styles.footerText}>Dashboard Footer</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: {
flex: 1,
backgroundColor: '#F3F4F6',
},
header: {
padding: 20,
backgroundColor: '#1D4ED8',
},
headerTitle: {
fontSize: 24,
fontWeight: 'bold',
color: '#FFFFFF',
},
headerSubtitle: {
marginTop: 4,
fontSize: 14,
color: '#DBEAFE',
},
scrollContent: {
padding: 16,
gap: 16,
},
cards: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 12,
},
card: {
flexGrow: 1,
flexBasis: 100,
padding: 16,
borderRadius: 12,
},
blueCard: {
backgroundColor: '#BFDBFE',
},
greenCard: {
backgroundColor: '#BBF7D0',
},
orangeCard: {
backgroundColor: '#FED7AA',
},
cardLabel: {
fontSize: 14,
color: '#374151',
},
cardValue: {
marginTop: 8,
fontSize: 24,
fontWeight: 'bold',
color: '#111827',
},
contentPanel: {
padding: 20,
borderRadius: 12,
backgroundColor: '#FFFFFF',
},
panelTitle: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 8,
color: '#111827',
},
panelText: {
fontSize: 15,
lineHeight: 22,
color: '#4B5563',
},
footer: {
padding: 16,
alignItems: 'center',
backgroundColor: '#E5E7EB',
},
footerText: {
fontSize: 14,
color: '#374151',
},
});
Project Explanation
- Screen: Uses
flex: 1 to occupy available space.
- Header: Uses padding and a background color to create a clear top section.
- ScrollView: Allows the dashboard content to scroll when it exceeds the available height.
- Cards container: Uses
flexDirection: 'row' and flexWrap: 'wrap' to arrange summary cards.
- Card sizing: Uses
flexGrow and flexBasis to allow cards to adapt to available width.
- Content panel: Uses padding and a column-style content structure.
- Footer: Uses alignment properties to center the footer text.
Note: The example uses gap, so confirm support in the React Native version used by your project. If necessary, replace gaps with suitable margins.
30. Practice Exercises
Exercise 1: Direction
- Create three colored boxes.
- Arrange them vertically using
column.
- Change the direction to
row.
- Try both reverse directions and observe the order.
Exercise 2: Alignment
- Create a container with three children.
- Test
justifyContent with center, space-between, and space-evenly.
- Change
alignItems and observe the cross-axis alignment.
Exercise 3: Flexible Space
- Create three children with flex values of 1, 2, and 3.
- Observe their relative sizes.
- Change the values and compare the results.
Exercise 4: Wrapping
- Create multiple cards inside a row container.
- Enable
flexWrap: 'wrap'.
- Change the card width and available container width.
- Experiment with
alignContent.
Exercise 5: Responsive Profile Screen
- Create a profile screen with a header, profile details, and action buttons.
- Use Flexbox for the major layout sections.
- Test the screen on different device widths.
- Check for text overflow and inconsistent spacing.
31. Interview Questions and Answers
Q1. What is Flexbox in React Native?
Answer: Flexbox is a layout system used to arrange child components, distribute available space, and control alignment within a parent container.
Q2. What is the default flexDirection in React Native?
Answer: The default value is column, so children are arranged vertically.
Q3. What is the difference between justifyContent and alignItems?
Answer: justifyContent aligns children along the main axis, while alignItems aligns them along the cross axis.
Q4. What is the main axis?
Answer: The main axis is the direction in which children are arranged, as determined by flexDirection.
Q5. What is the cross axis?
Answer: The cross axis is perpendicular to the main axis.
Q6. What does flex: 1 mean?
Answer: It allows a component to use available space according to the surrounding Flexbox layout. The exact size depends on the parent, siblings, and other layout constraints.
Q7. What is the difference between flexGrow and flexShrink?
Answer: flexGrow distributes remaining space among children, while flexShrink controls how children shrink when their combined size exceeds the available space.
Q8. What is flexBasis?
Answer: flexBasis specifies the initial size of an item along the main axis before flexible growth or shrinking is calculated.
Q9. What is flexWrap?
Answer: It controls whether children can move onto additional lines when they no longer fit on one line.
Q10. What is alignContent?
Answer: It controls the distribution of multiple wrapped lines along the cross axis.
Q11. What is alignSelf?
Answer: It allows an individual child to override the parent's cross-axis alignment for that child.
Q12. How do you center a component in React Native?
Answer: For centering along both axes, use justifyContent: 'center' and alignItems: 'center' on a parent with sufficient dimensions.
Q13. How can Flexbox help create responsive layouts?
Answer: Flexbox distributes available space dynamically and can arrange, grow, shrink, or wrap children based on the container dimensions.
Q14. What is the difference between row and column?
Answer: row arranges children horizontally, while column arranges children vertically.
Q15. Why might a flex child not fill its parent?
Answer: The parent may not have a defined size, or other dimensions and layout constraints may prevent the child from expanding.
32. Quick Revision Checklist
- Understand the parent container and child components.
- Remember that React Native defaults to
flexDirection: 'column'.
- Identify the main axis and cross axis before adjusting alignment.
- Use
justifyContent to distribute children along the main axis.
- Use
alignItems to align children along the cross axis.
- Use
alignSelf to adjust one child independently.
- Understand the roles of
flex, flexGrow, flexShrink, and flexBasis.
- Use
flexWrap for multi-line layouts.
- Use
alignContent to distribute wrapped lines.
- Use
gap when supported by the project.
- Build layouts with flexible dimensions and test multiple screen sizes.
- Use the layout inspector to debug unexpected results.
33. Conclusion
Flexbox is one of the most important layout concepts in React Native. It provides a systematic way to arrange components, align content, distribute space, and build responsive mobile interfaces.
Start by mastering flexDirection, justifyContent, and alignItems. Then learn how flex, flexGrow, flexShrink, flexBasis, flexWrap, and alignContent influence layout behavior. Practicing with headers, cards, dashboards, and profile screens will help you apply these concepts to real applications.
For further learning, explore the React Native Training Course at JustAcademy and register for a course demo.
34. Additional Learning Resources