---
title: Build and test task filtering
description: Choose a filter, show matching tasks, explain empty results, and test each behavior.
url: https://expo-developer-guide.thally.app/guides/task-filtering
---

# Build and test task filtering

Choose a filter, show matching tasks, explain empty results, and test each behavior.

Your task list is running. Now let's make it easier to find what matters.

You'll add three filters—All, Active, and Completed—then test that they show the right tasks without changing or losing any data.

No new packages are needed.

1. **Add filter controls** — Let users choose which tasks to see.
2. **Show matching tasks** — Update the list based on the selection.
3. **Handle empty results** — Explain when no tasks match.
4. **Test the behavior** — Verify filtering, task updates, and empty states.

Each stage ends with a checkpoint. Finish it before moving on.

## Start from the unfiltered starter

Complete the [quickstart](/quickstart) first. Work in `examples/expo-task-starter/` and edit `App.tsx`. Start from the committed app, which has completion toggles but no filters. Keep its `toggleTask` handler and `__tests__/App.test.tsx` unchanged.

From the example directory, keep Metro running in one terminal:

```sh
npm start
```

Open a second terminal at the repository root and establish your validation routine:

```sh
cd examples/expo-task-starter
npm run typecheck
npm run lint
npm test
```

Expect **one passing suite and four passing tests**. At each checkpoint, rerun these three checks from this second terminal. Save edits and press `r` in the Metro terminal for a full reload before checking initial states.

## 1. Add filter controls

### Change

Immediately before `const initialTasks: Task[] = [` in `App.tsx`, add:

```tsx
type Filter = 'all' | 'active' | 'completed';

const filters: { value: Filter; label: string }[] = [
  { value: 'all', label: 'All' },
  { value: 'active', label: 'Active' },
  { value: 'completed', label: 'Completed' },
];
```

Inside `App`, replace the existing `tasks` state declaration with these two declarations:

```tsx
const [tasks, setTasks] = useState<Task[]>(initialTasks);
const [filter, setFilter] = useState<Filter>('all');
```

In `FlatList`, replace the entire `ListHeaderComponent={...}` prop with the following. The existing title and description stay inside the header, followed by the controls:

```tsx
ListHeaderComponent={
  <View style={styles.header}>
    <Text accessibilityRole="header" style={styles.heading}>Task starter</Text>
    <Text style={styles.description}>
      Tap a task to mark it complete. Tap again to bring it back.
    </Text>
    <View style={styles.filters}>
      {filters.map((option) => (
        <Pressable
          key={option.value}
          accessibilityRole="button"
          accessibilityLabel={option.label}
          accessibilityState={{ selected: filter === option.value }}
          onPress={() => setFilter(option.value)}
          style={({ pressed }) => [
            styles.filterButton,
            filter === option.value && styles.selectedFilter,
            pressed && styles.pressedFilter,
          ]}
        >
          <Text
            style={[
              styles.filterLabel,
              filter === option.value && styles.selectedFilterLabel,
            ]}
          >
            {option.label}
          </Text>
        </Pressable>
      ))}
    </View>
  </View>
}
```

In `StyleSheet.create`, replace the existing `header` entry with the following entries. Keep the rest of the stylesheet:

```tsx
header: { marginBottom: 20, gap: 12 },
filters: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
filterButton: {
  minHeight: 48,
  minWidth: 48,
  justifyContent: 'center',
  alignItems: 'center',
  paddingHorizontal: 16,
  paddingVertical: 12,
  borderWidth: 2,
  borderColor: '#CBD3D8',
  borderRadius: 10,
  backgroundColor: '#FFFFFF',
},
selectedFilter: { borderColor: '#246247', backgroundColor: '#EDF5F1' },
pressedFilter: { opacity: 0.75 },
filterLabel: { fontSize: 16, color: '#172126' },
selectedFilterLabel: { fontWeight: '700' },
```

### Why

The `Filter` union limits the choice to three strings; `filter` stores the current choice, initially `'all'`. The controls use the existing imports and expose button labels and selected states to accessibility services.

A heavier label supplements the selected border and background, so the choice is not shown by color alone. Controls wrap and grow with larger text, with minimum 48-unit touch targets rather than fixed heights.

### Check

Reload: **All** starts selected. Press **Active** and **Completed**; selection should move, but **all three tasks stay visible**. Filtering comes next. Run the validation routine: the original **four tests** should pass.

If controls are missing, check that you replaced the header prop, not the whole list. For missing styles, compare the names and check that their entries are inside `StyleSheet.create`.

## 2. Show matching tasks

### Change

Replace the `filter` state declaration with this declaration and calculation, leaving `tasks` above it and `toggleTask` below it:

```tsx
const [filter, setFilter] = useState<Filter>('all');

const visibleTasks = tasks.filter((task) => {
  if (filter === 'active') return !task.completed;
  if (filter === 'completed') return task.completed;
  return true;
});
```

In `FlatList`, change only its `data` prop. Before:

```tsx
data={tasks}
```

After:

```tsx
data={visibleTasks}
```

### Why

`visibleTasks` is derived from the full task array and current choice on each render. Active keeps unfinished tasks; Completed keeps finished tasks; All keeps everything. There is no second array in state to synchronize and no effect or memoization needed for three tasks.

Leave `toggleTask`, `keyExtractor`, and `renderItem` unchanged. Updating only the visible array would lose hidden tasks. The new derived array also lets `FlatList` receive the changed data without adding `extraData`.

### Check

Reload, then select each filter:

| Filter | Expected initial tasks |
| --- | --- |
| All | All three tasks |
| Active | Run the app on your phone; Mark a task complete |
| Completed | Explore the starter code |

Complete **Run the app on your phone** while viewing Active. It should disappear there and appear checked under Completed and All. Reopen it from Completed: it leaves that view and returns to Active. Filtering changes what you see; toggling changes completion state.

Run the validation routine: **four tests** should pass. If every filter still shows three tasks, check `data={visibleTasks}`. If the initial view has fewer, check that `filter` starts as `'all'`.

## 3. Handle empty results

### Change

Immediately before `function toggleTask(id: string) {`, add:

```tsx
const emptyMessage =
  filter === 'active'
    ? 'No active tasks. Everything is complete.'
    : filter === 'completed'
      ? 'No completed tasks yet.'
      : 'No tasks to show.';
```

In `FlatList`, replace the consecutive `data={visibleTasks}` and `keyExtractor` props with:

```tsx
data={visibleTasks}
ListEmptyComponent={
  <Text style={styles.emptyMessage}>{emptyMessage}</Text>
}
keyExtractor={(task) => task.id}
```

In `StyleSheet.create`, replace the `selectedFilterLabel` entry with:

```tsx
selectedFilterLabel: { fontWeight: '700' },
emptyMessage: { fontSize: 17, lineHeight: 26, color: '#46545C', paddingVertical: 20 },
```

### Why

`ListEmptyComponent` explains why no rows match instead of leaving a blank list. Its message follows the selected filter. The All fallback is defensive: this starter has no delete action. The controls stay in the list header, available when no rows match and inside the scrolling content when text grows.

### Check

**No active tasks:** Reload, select Active, and complete **Run the app on your phone** and **Mark a task complete**. Expect **No active tasks. Everything is complete.** Return to All: all three tasks remain and are complete.

**No completed tasks:** Reload to restore the initial state, select Completed, and reopen **Explore the starter code**. Expect **No completed tasks yet.** Return to All: all three remain and are incomplete.

Run the validation routine: **four tests** should still pass. If the message is missing, check the `ListEmptyComponent` prop and its style name. You should still be able to change filters from either empty view.

## 4. Test the behavior

Jest and React Native Testing Library are already configured. Keep the original four starter tests. Add the following tests beside them; no package installation is needed.

### Start with the selected state

Create `__tests__/Filtering.test.tsx` with these complete contents:

```tsx
import { render, screen } from '@testing-library/react-native';
import App from '../App';

test('starts on All and exposes the selected filter', async () => {
  await render(<App />);
  expect(screen.getAllByRole('checkbox')).toHaveLength(3);
  expect(screen.getByRole('button', { name: 'All', selected: true })).toBeOnTheScreen();
  expect(screen.getByRole('button', { name: 'Active', selected: false })).toBeOnTheScreen();
  expect(screen.getByRole('button', { name: 'Completed', selected: false })).toBeOnTheScreen();
});
```

`render` creates the test screen; `screen` finds its controls. The role, label, and `selected` queries check the accessibility state, not just visible text. Run `npm test`: expect **two suites and five passing tests**. If it fails, check the initial filter and `accessibilityState.selected`.

### Check matching views

To trigger presses, replace the first import line with:

```tsx
import { fireEvent, render, screen } from '@testing-library/react-native';
```

Immediately after both imports and before the first test, add:

```tsx
const runTitle = 'Run the app on your phone';
const completeTitle = 'Mark a task complete';
const exploreTitle = 'Explore the starter code';

async function selectFilter(name: string) {
  await fireEvent.press(screen.getByRole('button', { name }));
}
```

Open the [complete filtering tests](/references/task-filtering/Filtering.test.tsx.txt). Copy the entire second `test(...)` block, named `shows the matching tasks without changing their status`, and append it after your first test. Include its closing `});`; do not copy the imports or helpers again.

This test checks Active and Completed membership and selected states, then returns to All to check that switching views preserved completion states. Run `npm test`: expect **two suites and six passing tests**.

### Check transitions and empty views

From the same [reference test file](/references/task-filtering/Filtering.test.tsx.txt), append the last two complete `test(...)` blocks, including their closing `});` lines:

- `removes completed tasks from Active and preserves them in All`
- `removes reopened tasks from Completed and explains an empty view`

They complete the remaining Active tasks or reopen the Completed task, check the exact empty messages and available controls, then return to All to verify the full task array and updated states.

Run the validation routine: expect **two suites and eight passing tests**. If tasks disappear permanently, check that `toggleTask` still updates `tasks`. For empty-message failures, compare the exact strings and list prop.

## Compare with the complete reference

The [completed screen](/references/task-filtering/App.tsx.txt) and [full filtering test file](/references/task-filtering/Filtering.test.tsx.txt) are plain-text downloads. Open a link and save the complete text, removing only the final `.txt` from its filename:

- Save the screen as `App.tsx` in your local example.
- Save the tests as `__tests__/Filtering.test.tsx`, alongside the unchanged `App.test.tsx`.

Replacing the screen skips the implementation checkpoints; use it to compare your work or recover after a blocked edit. These files use the starter's existing packages and settings. Run the validation routine after copying them: **eight tests** should pass.

## Check on your phone

Increase system text size and check wrapping, scrolling, and safe areas. With VoiceOver or TalkBack, check filter labels and selected-state announcements, access to controls beside empty messages, and where focus moves after a task disappears. Mocked tests cannot establish those native behaviors.

The earlier iPhone launch report applies to the unfiltered starter, not these filters. See the [validation record](https://github.com/Adejuwon-00/expo-developer-guide/blob/main/assessment/phase-3-validation.md) for automated results and unverified device checks.

You now have one task array and a view derived from a separate filter choice. Keep these behavior tests when you make your next change.

For more detail, see [React state](https://react.dev/learn/state-a-components-memory), [React Native accessibility](https://reactnative.dev/docs/accessibility), [FlatList](https://reactnative.dev/docs/flatlist), and [Expo testing](https://docs.expo.dev/develop/unit-testing/).