Skip to main content

Styling and Layout with Flexbox in React Native

Your goal: Turn the interactive Reading List into a readable, flexible screen while keeping each book’s read/unread toggle.

Before you begin: Complete Props and State. Open the same Expo project and run npx expo start.

By the end, you will be able to:

  • Write inline styles and organize reusable styles with StyleSheet.create().
  • Predict how direction, alignment, spacing, and flexible sizing position children.
  • Explain Yoga’s role in layout.
  • Keep cards readable on narrow phones and with larger text.

Style with JavaScript objects​

React Native accepts JavaScript objects through the style prop. Property names usually use camelCase, such as backgroundColor. Numeric dimensions such as padding: 16 describe logical, density-independent units, not physical screen pixels. Do not write padding: '16px'.

A small styled component
import { Text, View } from 'react-native';

function ReadingNote() {
return (
<View style={{ backgroundColor: '#eef2ff', padding: 16 }}>
<Text style={{ color: '#172554', fontSize: 18, fontWeight: '600' }}>
Make room for a good book
</Text>
</View>
);
}

The outer braces enter JavaScript; the inner braces create the style object. React Native styles resemble CSS, but native views do not use browser stylesheets, selectors, or the browser cascade. Put text styles on Text, not on its surrounding View. Nested Text can inherit text styling, but a parent View does not set the font for all its children. See the official style guide and Text reference.

These properties are enough to start designing a card:

PropertyPurposeExample value
backgroundColorFill the component’s background'#ffffff'
colorSet text color'#172554'
fontSizeSize the text18
fontWeightSet text weight'600'
paddingSpace inside a component’s border16
marginSpace outside a component8
borderWidthSet border thickness1
borderColorColor the border'#cbd5e1'
borderRadiusRound the corners16

Give styles names​

Inline objects are useful for small demonstrations. For our full screen, named styles keep JSX easier to read:

A named style
import { StyleSheet, Text, View } from 'react-native';

function ReadingNote() {
return (
<View style={styles.card}>
<Text style={styles.label}>Choose your next book</Text>
</View>
);
}

const styles = StyleSheet.create({
card: { padding: 16, backgroundColor: '#eef2ff', borderRadius: 16 },
label: { color: '#172554', fontSize: 18 },
});

StyleSheet.create() organizes style objects and helps your editor check property names and values. It does not create a browser CSS class.

A style array combines styles. Later entries override earlier entries for the same property:

Inside a card that already has isRead state
<Text style={[styles.status, isRead && styles.readStatus]}>
Status: {isRead ? 'Read' : 'Unread'}
</Text>

Here styles.status always applies. When isRead is true, styles.readStatus adds a different color and background; when false, that array entry is ignored. The complete example defines both styles.

Let Yoga calculate the layout​

React Native uses Yoga to calculate the sizes and positions of native views from their layout styles and the available space. You describe relationships—“put these children in a row” or “let this child fill the remaining space”—instead of calculating every coordinate. Yoga calculates layout; it does not draw the interface. Read About Yoga.

Flexbox arranges a container’s children along a main axis. The cross axis runs perpendicular to it. React Native defaults to flexDirection: 'column'; browser CSS Flexbox defaults to row.

Axes for a left-to-right layout
COLUMN (default) ROW
cross axis → main axis →
┌──────────────┐ ┌──────────────────┐
│ A │ │ A B C │
│ B │ │ │
│ C │ └──────────────────┘
└──────────────┘ cross axis ↓
main axis ↓

The diagrams show direction, not exact sizes. For these examples, assume a left-to-right language. Changing flexDirection changes which axis is main:

Container propertyColumnRow
justifyContentDistributes children verticallyDistributes children horizontally
alignItemsAligns children horizontallyAligns children vertically

The official Flexbox guide includes interactive examples and the full list of values.

Try five small layouts​

These fragments assume View and Text are imported from react-native. Try one at a time inside your screen. The fixed heights below make empty space visible for learning; the book cards later grow with their content.

1. Stack a column​

<View style={{ flexDirection: 'column', gap: 12 }}>
<Text>First book</Text>
<Text>Second book</Text>
<Text>Third book</Text>
</View>

Each child sits below the previous one. gap: 12 adds space between children, not around the container’s outside edge. Removing flexDirection leaves the same result because column is the default.

2. Make a row​

<View style={{ flexDirection: 'row', gap: 12 }}>
<Text>A</Text>
<Text>B</Text>
<Text>C</Text>
</View>

The children now sit beside each other. A row does not automatically wrap onto another line. For a set of short labels, adding flexWrap: 'wrap' lets children continue on another line when they do not fit. Wrapping children and wrapping text inside one child are different things.

3. Distribute spare space with justifyContent​

<View style={{ height: 160, justifyContent: 'space-between' }}>
<Text>Top</Text>
<Text>Middle</Text>
<Text>Bottom</Text>
</View>

This column puts the first child at the top, the last at the bottom, and distributes the leftover vertical space between them. Try 'center' to group them in the middle, or 'flex-start' to group them at the top. If a container is only as tall as its content, there is no spare height to distribute.

Same column height, different distribution
flex-start center space-between
┌─────────┐ ┌─────────┐ ┌─────────┐
│ A │ │ │ │ A │
│ B │ │ │ │ │
│ C │ │ A │ │ │
│ │ │ B │ │ B │
│ │ │ C │ │ │
│ │ │ │ │ │
│ │ │ │ │ C │
└─────────┘ └─────────┘ └─────────┘

4. Align across a row​

<View style={{ flexDirection: 'row', height: 100, alignItems: 'center', gap: 12 }}>
<Text style={{ fontSize: 32 }}>A</Text>
<Text style={{ fontSize: 16 }}>B</Text>
</View>

The cross axis is vertical, so 'center' centers both children vertically. Change it to 'flex-start' to align their top edges. The default, 'stretch', stretches eligible children across the cross axis when they have no explicit size there. In a column, that default helps our cards fill the available width.

5. Give a child the remaining space​

<View style={{ flexDirection: 'row', gap: 12 }}>
<View style={{ width: 48, backgroundColor: '#c7d2fe' }} />
<View style={{ flex: 1, padding: 12, backgroundColor: '#eef2ff' }}>
<Text>The book details use the remaining row width.</Text>
</View>
</View>

The first child reserves 48 units; the second uses the remaining width after the gap. With two otherwise equal flex: 1 children, the available space is shared equally. Flexible sizing needs a parent with available space: adding flex: 1 cannot create height inside an unconstrained container. See height and width.

Plan the Reading List’s new appearance​

The previous lesson gave us bordered cards and working buttons. We will keep the same three books and each card’s local useState(false).

BeforeAfter
Plain bordered entriesRounded white cards on a soft background
Title and author stacked aloneBook emoji beside a flexible details column
Basic status textA rounded status label with words and color
Fixed screen with practice top paddingScrollable content inside device-aware safe edges
Basic spacingConsistent padding and gaps, with room for long text

The action stays below the details so a long title does not compete with the button for row width. Status remains written as Read or Unread, so color is never the only cue.

Make room on different phones​

Let cards stretch to their parent’s width instead of setting a phone-sized width such as width: 360. Use modest padding and gaps to leave room for text. Responsive spacing does not always require breakpoints: start with one comfortable spacing scale and let the content area grow or shrink.

Inside a row, long text needs a width constraint to wrap. Our details container uses flex: 1. If a Text sits directly beside another item in a row, flexShrink: 1 lets it give up width and wrap instead of pushing its sibling outside the screen:

<View style={{ flexDirection: 'row', gap: 8 }}>
<Text>📖</Text>
<Text style={{ flexShrink: 1 }}>A long book title can wrap onto another line</Text>
</View>

React Native’s default flexShrink is 0, so ask for shrinking when you need it. Avoid fixed card heights and single-line limits for essential text. A ScrollView keeps the last card reachable on a short screen; its style sizes the scrolling viewport, while contentContainerStyle styles the content inside it. See the ScrollView reference.

Respect safe areas​

Safe-area insets protect content from notches, system bars, and home indicators. The default Expo Router project from Development Environment already includes react-native-safe-area-context and provides the surrounding safe-area context. Keep its layout files and use that library’s SafeAreaView, as below. Do not import the deprecated SafeAreaView from react-native.

The example protects all edges. If your existing navigator already handles an edge with a visible header or tab bar, adjust the wrapper’s edges prop to cover only unhandled edges if you see doubled spacing. For an alternative App.tsx setup, ensure there is a SafeAreaProvider at the app root. Follow Expo’s safe-area guide for your existing setup; the default Router project needs no additional installation for this lesson.

Run the complete styled screen​

Replace src/app/index.tsx with this example, or use the same screen file you edited in Props and State if your template differs. HomeScreen is the default export of this Expo Router screen; its filename determines the route. Keep the existing Router layout and routes. This is the only complete implementation; the earlier snippets were isolated demonstrations.

src/app/index.tsx — complete example
import { useState } from 'react';
import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

type BookCardProps = {
title: string;
author: string;
};

function BookCard({ title, author }: BookCardProps) {
const [isRead, setIsRead] = useState(false);
const buttonLabel = isRead ? 'Mark as unread' : 'Mark as read';

return (
<View style={styles.card}>
<View style={styles.bookRow}>
<Text
style={styles.bookIcon}
accessible={false}
accessibilityElementsHidden={true}
importantForAccessibility="no"
>
📖
</Text>
<View style={styles.details}>
<Text style={styles.bookTitle}>{title}</Text>
<Text style={styles.author}>{author}</Text>
</View>
</View>
<Text style={[styles.status, isRead && styles.readStatus]}>
Status: {isRead ? 'Read' : 'Unread'}
</Text>
<Pressable
style={({ pressed }) => [styles.button, pressed && styles.buttonPressed]}
onPress={() => setIsRead(previous => !previous)}
accessibilityRole="button"
accessibilityLabel={buttonLabel + ': ' + title}
>
<Text style={styles.buttonText}>{buttonLabel}</Text>
</Pressable>
</View>
);
}

function ReadingListScreen() {
return (
<SafeAreaView style={styles.screen}>
<ScrollView contentContainerStyle={styles.content}>
<View style={styles.header}>
<Text style={styles.heading} accessibilityRole="header">
My Reading List
</Text>
<Text style={styles.subtitle}>Three books to explore next</Text>
</View>
<BookCard title="The Hobbit" author="J. R. R. Tolkien" />
<BookCard title="A Wizard of Earthsea" author="Ursula K. Le Guin" />
<BookCard title="The Secret Garden" author="Frances Hodgson Burnett" />
</ScrollView>
</SafeAreaView>
);
}

export default function HomeScreen() {
return <ReadingListScreen />;
}

const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#f1f5f9' },
content: { padding: 16, gap: 16 },
header: { gap: 6, marginBottom: 4 },
heading: { color: '#0f172a', fontSize: 28, fontWeight: '700' },
subtitle: { color: '#475569', fontSize: 16 },
card: {
padding: 16,
gap: 12,
backgroundColor: '#ffffff',
borderWidth: 1,
borderColor: '#cbd5e1',
borderRadius: 16,
},
bookRow: { flexDirection: 'row', alignItems: 'flex-start', gap: 12 },
bookIcon: { fontSize: 28, flexShrink: 0 },
details: { flex: 1, gap: 4 },
bookTitle: { color: '#0f172a', fontSize: 20, fontWeight: '600' },
author: { color: '#475569', fontSize: 16 },
status: {
alignSelf: 'flex-start',
maxWidth: '100%',
paddingHorizontal: 10,
paddingVertical: 6,
borderRadius: 8,
backgroundColor: '#e2e8f0',
color: '#334155',
fontSize: 14,
fontWeight: '600',
},
readStatus: { backgroundColor: '#dcfce7', color: '#166534' },
button: {
minHeight: 48,
padding: 12,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#1e40af',
borderRadius: 10,
},
buttonPressed: { backgroundColor: '#1e3a8a' },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', textAlign: 'center' },
});

Read the layout from outside in​

  • screen.flex: 1 fills the available screen area. The ScrollView has a bounded viewport inside that screen, so longer content can scroll.
  • content gives the heading and cards a shared inset and consistent gaps. Column layout and the default stretch alignment keep cards full width within that padding.
  • bookRow puts the icon beside the details. Top alignment keeps the icon near the first line when a title wraps. details.flex: 1 uses the remaining row width.
  • status.alignSelf overrides the parent’s alignment for this one child, letting the label hug its content. maxWidth keeps it within the card; it can grow taller with larger text.
  • button centers its label on both axes. minHeight gives a generous touch area without preventing the button from growing. The pressed style callback provides visible press feedback.

The emoji is decorative, so its accessibility properties hide it from screen readers. Each button keeps the action-and-book label from the previous lesson. No interaction logic moved: each card still owns its state, and reloading the app resets it. This example uses an explicit light palette for the native screen; automatic app theme switching is outside this lesson.

Try it on your device: Toggle only The Hobbit, then scroll to The Secret Garden and toggle it. Confirm the other card stays unread. Try a narrow portrait screen, landscape, and a larger accessibility text size in the device settings. Every title, status, and button should remain readable, and the last button should remain reachable by scrolling. Keep font scaling enabled; adjust layout instead of reducing users’ chosen text size.

Fix common layout mistakes​

If you see…Check this
Items stack when you expected a rowSet flexDirection: 'row' on their parent.
Centering moves items in the wrong directionIdentify the main axis first; justifyContent follows it.
justifyContent appears to do nothingCheck whether the parent has spare space to distribute.
Long text pushes an icon offscreenGive the details container flex: 1, or the direct text child flexShrink: 1.
Text color does not changeApply color to Text, not its surrounding View.
Spacing doubles between cardsAvoid combining sibling margins and parent gap unintentionally.
The last button is clippedUse a bounded scrolling viewport and let cards grow with text.
Content overlaps system UICheck safe-area handling instead of adding guessed top padding.

Practice​

  1. Restyle a card. Change its padding and background color. Keep the text readable and compare inside spacing with the gap between cards.
  2. Move the status. Try placing it beside the book details using Flexbox. Decide what should shrink or wrap, then check a long title and larger text before keeping the change.
  3. Improve a narrow layout. Temporarily use a much longer title and the largest accessibility text size. Adjust spacing where needed without fixed card heights or hiding text. Verify you can still reach all three buttons.

Check your understanding​

  1. In a row, which property centers children vertically?
  2. Why might justifyContent: 'space-between' have no visible effect?
  3. What does Yoga calculate, and what does flex: 1 do in the book-details row?
  4. Why use a minimum button height instead of a fixed height?
Compare your answers

alignItems controls the row’s vertical cross axis. Space distribution needs leftover space in the parent. Yoga calculates layout sizes and positions; the flexible details container takes the row width left after the icon and gap. A minimum height keeps the touch area comfortable while allowing the button to grow with its text.

You are ready to continue when: You can explain both axes, restyle all three cards through one style definition, and keep their independent toggles usable on a smaller screen.

Return to the learning path for further resources.

Official references​