Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 71 ยท Practice and Review

Exercises: Components, Styles and Lists

Eight graded React Native exercises on Flexbox layout, Pressable feedback, FlatList search, keys and immutable updates, each with a hint, a solution and a live stand-in.

Reading about React Native teaches you the vocabulary. Writing screens teaches you the language. This page gives you eight small exercises that move from "put three things in a row" to "filter a list and toggle an item without mutating state". They use only ideas from the first four chapters: core components, Flexbox, Pressable and FlatList.

Read-only and stand-in. Real React Native code needs a native runtime, so the solutions are shown as plain code blocks that you would paste into an Expo project. Next to them are live stand-ins: small components that accept the same props and style names and draw them with HTML, so you can check the logic (layout rules, pressed state, filtering, keys) right here. The stand-ins are not React Native; they are a model of it.

How to use these exercises

Read the task Say the goal in one sentence.
Try first Give it five minutes before the hint.
Open the hint It points; it does not solve.
Compare Study how the solution differs.

Struggling for a few minutes is where the learning happens.

1 / 2

A few habits help across all eight exercises:

  • Describe the state before you write code. What is the smallest set of values that explains the screen? Everything else is computed while rendering.
  • Never change state in place. Make a new array or object and pass it to the setter.
  • Give every list row a stable key from the data, never from its position in a list that can change.
  • Put every string inside a <Text>. A bare string inside a View crashes the app.

Layout with Flexbox

Flexbox in React Native is the same idea as on the web with different defaults: the main axis is vertical (flexDirection: 'column'), and flexShrink defaults to 0. If you are rusty, revisit Flexbox in React Native.

1. A profile row

Build a row with a round avatar showing initials on the left, a name and a role stacked in the middle, and a small badge on the right. The middle part must take all remaining width, everything must be vertically centered, and the parts must be separated by a gap of 12.

Show hint

The outer View needs flexDirection: 'row' and alignItems: 'center'. A circle is a square with borderRadius equal to half its size. Give the middle column flex: 1 so it grows to fill the free space; the badge and avatar keep their natural size. Use gap: 12 on the row instead of margins on every child.

Show solution
TSX
import { StyleSheet, Text, View } from 'react-native';

export function ProfileRow() {
  return (
    <View style={styles.row}>
      <View style={styles.avatar}>
        <Text style={styles.avatarText}>AL</Text>
      </View>
      <View style={styles.info}>
        <Text style={styles.name}>Ada Lovelace</Text>
        <Text style={styles.role}>Engineer</Text>
      </View>
      <View style={styles.badge}>
        <Text style={styles.badgeText}>PRO</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  row: { flexDirection: 'row', alignItems: 'center', gap: 12, padding: 16 },
  avatar: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: '#6366f1',
    alignItems: 'center',
    justifyContent: 'center',
  },
  avatarText: { color: 'white', fontWeight: '700' },
  info: { flex: 1 },
  name: { fontSize: 16, fontWeight: '600' },
  role: { fontSize: 13, color: '#64748b' },
  badge: { backgroundColor: '#dcfce7', borderRadius: 6, paddingHorizontal: 8, paddingVertical: 2 },
  badgeText: { color: '#166534', fontSize: 12, fontWeight: '700' },
});

The row is the main axis (horizontal), so alignItems centers on the cross axis (vertical). flex: 1 is shorthand for "grow to fill, with a basis of zero".

Make a bar with three boxes whose widths are in the ratio 1 : 2 : 1. Then build a screen where a header sits at the top, a footer sits at the bottom, and the body fills everything between them, even when there is little content.

Show hint

Ratios are flex values on siblings: flex: 1, flex: 2, flex: 1 split the free space 25 / 50 / 25 percent. For the screen, the root View needs flex: 1 (otherwise it is only as tall as its content) and the body needs flex: 1 too. Alternatively give the root justifyContent: 'space-between'.

Show solution
TSX
function Screen() {
  return (
    <View style={{ flex: 1 }}>
      <View style={{ height: 56, backgroundColor: '#e0e7ff' }}><Text>Header</Text></View>
      <View style={{ flex: 1, padding: 16 }}><Text>Body</Text></View>
      <View style={{ height: 56, backgroundColor: '#e0e7ff' }}><Text>Footer</Text></View>
    </View>
  );
}

function RatioBar() {
  return (
    <View style={{ flexDirection: 'row', height: 40 }}>
      <View style={{ flex: 1, backgroundColor: '#fca5a5' }} />
      <View style={{ flex: 2, backgroundColor: '#fde68a' }} />
      <View style={{ flex: 1, backgroundColor: '#86efac' }} />
    </View>
  );
}

flex values are relative to each other, not percentages of the parent. Three siblings with flex: 1 each get a third.

Here is a stand-in for both exercises. View converts React Native style names to CSS the way React Native's defaults work (column direction, no shrinking), so the layout you see follows the same rules.

Exercises 1 and 2: profile row and flex ratios

Touch and feedback

3. A button with pressed and disabled states

Create a LikeButton. It shows "Like" or "Liked" with a count. While the finger is down, the button looks darker. When disabled is true, it looks faded and ignores presses. A press toggles the liked state and changes the count by one.

Show hint

Pressable accepts a function for style. It receives { pressed }, so you can return a different style while the finger is down. Pass disabled to stop presses, and use the functional form of the setter when the next state depends on the previous one: setCount((c) => c + 1).

Show solution
TSX
import { useState } from 'react';
import { Pressable, StyleSheet, Text } from 'react-native';

export function LikeButton({ disabled = false }: { disabled?: boolean }) {
  const [liked, setLiked] = useState(false);
  const [count, setCount] = useState(12);

  function toggle() {
    setLiked((value) => !value);
    setCount((c) => (liked ? c - 1 : c + 1));
  }

  return (
    <Pressable
      onPress={toggle}
      disabled={disabled}
      accessibilityRole="button"
      accessibilityState={{ disabled, selected: liked }}
      style={({ pressed }) => [
        styles.button,
        liked && styles.liked,
        pressed && styles.pressed,
        disabled && styles.disabled,
      ]}
    >
      <Text style={styles.label}>{liked ? 'Liked' : 'Like'} ({count})</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  button: { backgroundColor: '#6366f1', paddingVertical: 12, paddingHorizontal: 20, borderRadius: 8 },
  liked: { backgroundColor: '#db2777' },
  pressed: { opacity: 0.7 },
  disabled: { opacity: 0.4 },
  label: { color: 'white', fontWeight: '600', textAlign: 'center' },
});

Style arrays are merged left to right, so the last matching style wins. There is no cascade in React Native: you build the final style from what you pass.

4. A tiny icon button that is easy to hit

A 20 by 20 close icon is nearly impossible to tap. Make the touchable area at least 44 by 44 points without making the icon bigger or shifting the layout.

Show hint

Two tools do this. hitSlop extends the touchable area beyond the element's visual bounds. Alternatively, add padding to the Pressable itself so the box grows around the icon. Remember the guideline: about 44 points on iOS and 48 on Android.

Show solution
TSX
<Pressable
  onPress={onClose}
  hitSlop={12}            // 20 + 12 + 12 = 44 points each way
  accessibilityRole="button"
  accessibilityLabel="Close"
>
  <CloseIcon size={20} />
</Pressable>

hitSlop={12} adds 12 points on every side. hitSlop does not change layout, but neighbouring touchables can overlap its area, so keep the slop smaller than the gap between buttons. When there is room, padding is the safer choice because it also makes the pressed feedback bigger.

The stand-in below reproduces exercises 3 and 4 with a Pressable that tracks pressed with pointer events and accepts a style function. Press and hold the button to see the darker state; the second button is disabled.

Exercises 3 and 4: pressed, disabled and hit area

Lists

5. A searchable list with an empty state

Show a list of contacts. A search box above the list filters by name, ignoring case. When nothing matches, show "No contacts found". Rows must use a stable key.

Show hint

Keep one piece of state: the query. Derive the visible array during render with filter. Do not store the filtered list in state; it would go stale when the data or the query changes. Use ListEmptyComponent for the empty message and keyExtractor (or an id field) for keys. Put the TextInput in ListHeaderComponent, or above the list, and set keyboardShouldPersistTaps="handled" so taps on rows work while the keyboard is open.

Show solution
TSX
import { useMemo, useState } from 'react';
import { FlatList, Text, TextInput, View } from 'react-native';

type Contact = { id: string; name: string };

export function Contacts({ contacts }: { contacts: Contact[] }) {
  const [query, setQuery] = useState('');

  const visible = useMemo(() => {
    const needle = query.trim().toLowerCase();
    return contacts.filter((c) => c.name.toLowerCase().includes(needle));
  }, [contacts, query]);

  return (
    <View style={{ flex: 1 }}>
      <TextInput
        value={query}
        onChangeText={setQuery}
        placeholder="Search"
        autoCorrect={false}
        clearButtonMode="while-editing"
        style={{ padding: 12, borderBottomWidth: 1, borderColor: '#cbd5e1' }}
      />
      <FlatList
        data={visible}
        keyExtractor={(c) => c.id}
        keyboardShouldPersistTaps="handled"
        renderItem={({ item }) => <Text style={{ padding: 14 }}>{item.name}</Text>}
        ListEmptyComponent={<Text style={{ padding: 14 }}>No contacts found</Text>}
      />
    </View>
  );
}

The useMemo is an optimization, not a requirement: filtering a short list on every render is cheap. The important part is that visible is derived, never stored.

6. Toggle one row without mutating

Each row has a checkbox-like button. Pressing it must mark only that item done, and the list must re-render. Do it without changing the existing array or its objects.

Show hint

FlatList compares its props. If you mutate an object and pass the same array again, nothing changes as far as React can tell. Use map to build a new array in which only the matching item is replaced by a copy with done flipped: { ...item, done: !item.done }.

Show solution
TSX
function toggleDone(items: Todo[], id: string): Todo[] {
  return items.map((item) => (item.id === id ? { ...item, done: !item.done } : item));
}

// inside the component
const [todos, setTodos] = useState(initialTodos);
const onToggle = (id: string) => setTodos((current) => toggleDone(current, id));

Rows that did not change keep the same object, so a memoized row component skips them. If the row reads something that is not in data, such as selectedId, pass extraData={selectedId} so the list knows to re-render.

The stand-in FlatList below accepts the same props as in the previous lessons (data, renderItem, keyExtractor, ListEmptyComponent). It combines exercises 5 and 6: the search box starts with the query "co" so you can see a filtered result immediately.

Exercises 5 and 6: search, empty state and toggle

Fixing broken code

7. Find the crash

This screen crashes on a phone with "Text strings must be rendered within a Text component". Find all the causes.

TSX
function Greeting({ name, unread }: { name: string; unread: number }) {
  return (
    <View>
      Hello, {name}
      {unread && <Text>{unread} new messages</Text>}
    </View>
  );
}
Show hint

On the web, text can sit directly inside a div. In React Native, every piece of text must be inside a <Text>. Then look at the && line: what does it render when unread is 0?

Show solution
TSX
function Greeting({ name, unread }: { name: string; unread: number }) {
  return (
    <View>
      <Text>Hello, {name}</Text>
      {unread > 0 && <Text>{unread} new messages</Text>}
    </View>
  );
}

There were two bugs. First, Hello, {name} is bare text inside a View. Second, unread && ... evaluates to the number 0 when there are no messages, and 0 is rendered as a string outside any Text. Compare with a boolean (unread > 0) so the expression yields false, which renders nothing. The same crash happens with an empty string on the left of &&.

8. Stable keys

A list of editable rows keeps its typed text, but after the user deletes the first row, the remaining rows show the wrong text. The code uses keyExtractor={(item, index) => String(index)}. Explain the bug and fix it.

Show hint

React matches rows between renders by key. After a delete, which item sits at index 0? Which row component instance does React think it is?

Show solution

Change the extractor to a stable id from the data:

TSX
<FlatList
  data={notes}
  keyExtractor={(note) => note.id}
  renderItem={({ item }) => <NoteRow note={item} />}
/>

With index keys, deleting the first item shifts every other item up by one index. React reuses the row instance with key "0" for the item that is now first, and that instance still holds the previous item's local state (the typed text). A unique id from the data ties each row's state to the item itself, so deleting an item removes exactly its row.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a row, which style centers children vertically?

    In a row the main axis is horizontal, so alignItems works on the cross axis, which is vertical. justifyContent would center horizontally.
  2. 2. Three sibling Views have flex values 1, 2 and 1. How is the free space shared?

    flex values are relative weights. The total is 4, so the shares are 1/4, 2/4 and 1/4.
  3. 3. Which approach enlarges a small icon's touch target without changing the layout?

    hitSlop extends the touchable area beyond the visual bounds and does not move anything.
  4. 4. Why does {count && <Text>items</Text>} crash when count is 0?

    The expression evaluates to 0, a number that React Native tries to render as text without a Text parent. Use count > 0 instead.
  5. 5. Why should you avoid index keys for a list where items can be deleted?

    After a deletion the indexes shift, so React reuses old row instances (with their local state) for different items.

Summary

  • Flexbox defaults differ from the web: column direction and no shrinking. flex values are relative weights, and alignItems works on the cross axis.
  • Pressable takes a style function for pressed feedback; use disabled, accessibility props and hitSlop for good touch targets.
  • Keep the smallest state (a query, a list) and derive everything else during render; never mutate arrays or objects in state.
  • All text goes inside <Text>, and && needs a boolean on its left side.
  • Use stable ids as keys, and use ListEmptyComponent for the "nothing here" state.

Next, practise the harder parts in Exercises: Navigation, Data and Performance.