# Search screen with results

> A React Native search screen for iOS, Android and the web: a search field with recent searches, skeleton rows while results load, the matching results in a list, and an empty state with a way out when nothing matches. One file, built with Patine's SearchField, List, ListItem, Skeleton and EmptyState.

# Search with results

A bookshop's search: recent searches before you type, skeleton rows for the moment the results take, the matches with their author and price, and an empty state that suggests what to do when nothing matches. Try `lisbon`, `saramago` or `zzz`.

```tsx live device
import { useEffect, useState } from 'react';
import { ScrollView, StyleSheet, View } from 'react-native';
import { Button, EmptyState, List, ListItem, SearchField, Skeleton, Text, useTheme } from 'patine-ui';
import { Icon } from '@patine-ui/icons';

type Book = { id: number; title: string; author: string; price: number; tint: string };

const BOOKS: Book[] = [
  { id: 1, title: 'The Year of the Death of Ricardo Reis', author: 'José Saramago', price: 14.9, tint: '#E6DDD3' },
  { id: 2, title: 'Blindness', author: 'José Saramago', price: 12.5, tint: '#DCE5E0' },
  { id: 3, title: 'The Book of Disquiet', author: 'Fernando Pessoa', price: 16, tint: '#E3E1F0' },
  { id: 4, title: 'Night Train to Lisbon', author: 'Pascal Mercier', price: 13.9, tint: '#D8E6EE' },
  { id: 5, title: 'Lisbon: A Cultural History', author: 'Paul Buck', price: 18.5, tint: '#ECE7DF' },
  { id: 6, title: 'The Elephant’s Journey', author: 'José Saramago', price: 11.9, tint: '#E9E2D6' },
  { id: 7, title: 'The Return', author: 'Dulce Maria Cardoso', price: 12.9, tint: '#DDE7EC' },
];
const RECENT = ['Pessoa', 'Lisbon', 'Poetry in translation'];
const DELAY = 650;
// The demo's server: a short wait, then the books whose title or author holds every word.
const searchBooks = (query: string) =>
  new Promise<Book[]>((resolve) => {
    const words = query.toLowerCase().split(/\s+/).filter(Boolean);
    setTimeout(() => resolve(BOOKS.filter((b) => words.every((w) => `${b.title} ${b.author}`.toLowerCase().includes(w)))), DELAY);
  });

export default function Search() {
  const { colors, radius } = useTheme();
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<Book[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!query.trim()) return;
    let current = true;
    setLoading(true);
    searchBooks(query).then((found) => {
      // A slower answer to an older query must not replace a newer one.
      if (!current) return;
      setResults(found);
      setLoading(false);
    });
    return () => {
      current = false;
    };
  }, [query]);

  const searching = query.trim().length > 0;

  return (
    <View style={[styles.screen, { backgroundColor: colors.background }]}>
      <View style={styles.bar}>
        <SearchField value={query} onValueChange={setQuery} placeholder="Titles, authors, ISBN" onCancel={() => setQuery('')} />
      </View>

      {!searching ? (
        <ScrollView contentContainerStyle={styles.content}>
          <List title="Recent searches">
            {RECENT.map((term) => (
              <ListItem key={term} title={term} leading={<Icon name="history" size="sm" />} onPress={() => setQuery(term)} />
            ))}
          </List>
        </ScrollView>
      ) : loading ? (
        <View style={styles.skeletons} accessibilityLabel="Loading results">
          {[0, 1, 2, 3].map((i) => (
            <View key={i} style={styles.skeletonRow}>
              <Skeleton width={44} height={60} radius={6} />
              <View style={styles.skeletonText}>
                <Skeleton height={14} width="80%" />
                <Skeleton height={12} width="45%" />
              </View>
            </View>
          ))}
        </View>
      ) : results.length ? (
        <ScrollView contentContainerStyle={styles.content}>
          <Text size="sm" color="textSecondary" style={styles.count}>
            {results.length} {results.length === 1 ? 'book' : 'books'}
          </Text>
          <List>
            {results.map((b) => (
              <ListItem
                key={b.id}
                title={b.title}
                description={`${b.author} · €${b.price.toFixed(2)}`}
                leading={
                  <View style={[styles.cover, { backgroundColor: b.tint, borderRadius: radius.sm }]}>
                    <Icon name="book" size="sm" color="#00000066" />
                  </View>
                }
                onPress={() => {}}
              />
            ))}
          </List>
        </ScrollView>
      ) : (
        <EmptyState
          icon={<Icon name="search" size={40} color="textSecondary" />}
          title={`No books for “${query.trim()}”`}
          description="Check the spelling, or search by the author’s surname."
          action={
            <Button variant="outline" onPress={() => setQuery('')}>
              Clear search
            </Button>
          }
          style={styles.empty}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  screen: { flex: 1 },
  bar: { padding: 16, paddingBottom: 8 },
  content: { paddingVertical: 8 },
  count: { paddingHorizontal: 20, paddingBottom: 8 },
  skeletons: { gap: 18, padding: 20 },
  skeletonRow: { flexDirection: 'row', alignItems: 'center', gap: 14 },
  skeletonText: { flex: 1, gap: 8 },
  cover: { width: 32, height: 44, alignItems: 'center', justifyContent: 'center' },
  empty: { flex: 1 },
});
```

## Components used

- [SearchField](/docs/components/search-field): the search box, with a clear button and Cancel
- [List, ListItem](/docs/components/list): recent searches, then the results
- [Skeleton](/docs/components/skeleton): rows shaped like the results while they load
- [EmptyState](/docs/components/empty-state): no matches, with a button to start over
- [Button](/docs/components/button), [Text](/docs/components/text), [Patine Icons](/docs/components/icons)

## How it works

- **Old answers can't win.** Each search's effect clears a `current` flag when the query changes, so a slow reply to `lis` never overwrites the reply to `lisbon`.
- **Skeletons match the rows.** A cover and two lines, the same shape as a result, so nothing jumps when the books arrive.
- **The empty state says what to try** and offers a way back, instead of a blank screen.
- **Searching inside a field?** For a picker that searches a server as you type, see [Search a server](./server-search).
