Skip to main content

Building Forms and Handling User Input in React Native

Your goal: Open Add Book, enter a title and author with optional notes, and return to a Reading List that keeps your entry when remote books refresh.

Before you begin: Complete Networking and API Data. Use its Expo Router project, shared BooksProvider, and safe-area setup. This is Beginner Guide 10. These examples belong in your separate learning app; the publication remains statically generated.

By the end, you will be able to:

  • Connect a TextInput to React state and distinguish typing from submitting.
  • Validate required fields and explain errors without relying on color.
  • Move focus, dismiss the keyboard, and keep a short form scrollable.
  • Save a local book through the existing shared owner before navigating.
  • Keep local entries and remote results together without losing either on refresh.

Turn text into a controlled input​

A form groups editable fields and an action that uses their values. Static text only displays information; an input also needs focus, a keyboard, an editable value, and feedback when that value is not usable. React Native’s TextInput is a native input component, not an HTML input or form element.

Inside a component — the controlled-input pattern
const [title, setTitle] = useState('');

<TextInput
value={title}
onChangeText={setTitle}
placeholder="Book title"
/>

Import useState from react and TextInput from react-native. The initial value is an empty string. value supplies what the input displays; onChangeText receives the edited string and calls the setter. React renders again with that value. This is a controlled input: React state owns the displayed text. A placeholder is a hint when empty, not a value or a lasting label. The complete form includes visible and accessibility labels. See TextInput.

Typing changes a draft. Submitting validates that draft and adds one book. We do not add a book on every keystroke or use an Effect to watch for submission. A Pressable event handler performs that action.

From draft to shared book
Type → onChangeText → screen state → TextInput value
Press Add Book → trim and validate
invalid → field messages; stay on the form
valid → provider adds a local book → return to Reading List

Separate title, author, and notes state values are easy to follow for three fields. They hold only the unfinished draft, not a second book collection.

Validate before saving​

The idea behind the submit handler
const cleanTitle = title.trim();
const cleanAuthor = author.trim();
if (cleanTitle.length === 0 || cleanAuthor.length === 0) {
// Show field errors and return before adding anything.
return;
}

trim() removes surrounding whitespace without changing internal spaces. A title containing only " " becomes "" and fails validation. Notes are optional. We trim on submission so ordinary spaces remain easy to type while editing.

The full form sets attempted after the first submission. Error strings are then derived from the current input values. Fixing an invalid field immediately removes its message; clearing it again restores the message. This avoids keeping a stale copy of each error in state. Invalid submission focuses the first invalid input. Text messages accompany borders, and the input’s accessibility hint includes its current error.

Extend the existing state owner​

In Guide 09, src/data/books.ts performs the HTTPS search and maps the response. BooksProvider stores the fetched books, readById, and request state above the stack. Home and Details both read useBooks(); Details does not fetch a selected book independently.

We keep that design and make a small change:

Value in the providerResponsibility
remoteBooksLast successful Open Library search; only loadBooks replaces it.
localBooksEntries added through this form; refresh never replaces it.
booksDerived array: local entries first, then remote results. No separate setter.
readByIdCurrent read/unread status for either source.

The shared Book type gains optional notes. A new addBook function creates the entry and marks its ID unread. The form calls it through Context. Saving only in the form’s own state would leave Home unaware and lose the entry when the form unmounts. An ID remains the only book information sent through a Details URL.

The provider generates IDs once, during addition, using JavaScript’s built-in Date.now() plus an increasing useRef counter: local-<time>-<counter>. The counter prevents two additions in the same millisecond from colliding, even if the clock moves backward. The local- prefix cannot collide with Open Library’s OL…W IDs. This is unique within the single provider’s in-memory lifetime, not a cross-device UUID scheme. A persistence or synchronization design must revisit ID allocation before retaining entries across provider lifetimes. No ID-generation dependency is needed for this scope.

Local addition is not an API write

Add Book updates React state only. It sends no POST request, never uploads notes, and works even if the remote search fails. Open Library supplies book metadata; its search endpoint does not store this personal list.

Add a static route beside Details​

FileURLPurpose
src/app/index.tsx/Reading List
src/app/books/add.tsx/books/addAdd Book form
src/app/books/[id].tsx/books/OL29898642W or a local IDBook Details

The literal add.tsx route is more specific than [id].tsx, so /books/add opens the form. It is not a book with ID add. This follows Expo’s route notation and route-matching implementation. Adding Stack.Screen supplies the header title; its order is not a workaround for route matching. Keep the normal stack header and native back behavior.

Home pushes /books/add. After a successful save, router.dismissTo('/') returns to the existing Reading List; if it is absent from history, it replaces the current screen with /. This also handles opening the form directly. The Cancel control does the same without saving. See the Expo Router API.

Make room for the keyboard​

Focusing an input opens the software keyboard on a device without a hardware keyboard. The form uses Next on title and author to focus the following field through a ref. Notes is multiline, so Return inserts a newline. The Add Book button submits the whole form; pressing Next does not save it.

KeyboardAvoidingView makes room for the keyboard, while ScrollView lets users reach all three fields and the buttons on short screens. We use padding on iOS and height on Android as a starting point. useHeaderHeight accounts for the existing stack header rather than hardcoding its height. For the SDK 57 project used here, import it from expo-router/react-navigation. Expo Router in SDK 56 and later does not support application imports from @react-navigation/*; see the official import migration table. See KeyboardAvoidingView and useHeaderHeight.

keyboardShouldPersistTaps="handled" allows a button tap to reach its handler while the keyboard is visible. Dragging dismisses it, and a visible Hide keyboard control calls Keyboard.dismiss(). We also dismiss it after a valid submission. The header handles the top safe area; SafeAreaView from react-native-safe-area-context handles left, right, and bottom. Check Android resizing and iOS keyboard behavior on actual devices; they are not identical. See ScrollView and Keyboard.

Run the complete application​

What changes in this lesson: You can add a book even when the remote search fails, then open its Details and mark it read. These additions remain in memory until the app restarts.

  • Add src/app/books/add.tsx for the form and register it in _layout.tsx.
  • Add optional notes to src/data/books.ts and local additions to BooksProvider.tsx.
  • Update index.tsx to open the form and [id].tsx to display either local or remote books.
  • Reuse BookCard.tsx and the remote fetch helper unchanged.

All seven complete files are below; they replace the six files from Networking and add the form. Keep your working Expo configuration, the SDK 57 Router template dependencies (the header Hook comes from the existing expo-router package), and only one route root, src/app. No website package or form library is added.

Learning-app source files
src/
app/
_layout.tsx
index.tsx
books/
add.tsx
[id].tsx
components/
BookCard.tsx
data/
books.ts
state/
BooksProvider.tsx

1. Keep metadata and optional notes​

The only type change is notes?: string; the small GET request and response checks from Networking remain intact. Keep its API usage guidance: this is an occasional educational search, not a production backend.

src/data/books.ts
export type Book = {
id: string;
title: string;
author: string;
firstPublishYear?: number;
notes?: string;
};

type SearchDocument = {
key: string;
title?: string;
author_name?: string[];
first_publish_year?: number;
};

const SEARCH_QUERY = 'react native';
const SEARCH_URL = 'https://openlibrary.org/search.json?q='
+ encodeURIComponent(SEARCH_QUERY)
+ '&limit=10&fields=key,title,author_name,first_publish_year';

function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}

function readDocument(value: unknown): SearchDocument {
if (!isObject(value) || typeof value.key !== 'string'
|| !/^\/works\/OL\d+W$/.test(value.key)) {
throw new Error('The book service returned an invalid book identifier.');
}

return {
key: value.key,
title: typeof value.title === 'string' ? value.title : undefined,
author_name: Array.isArray(value.author_name)
? value.author_name.filter((name: unknown): name is string =>
typeof name === 'string' && name.trim().length > 0)
: undefined,
first_publish_year: typeof value.first_publish_year === 'number'
&& Number.isFinite(value.first_publish_year)
? value.first_publish_year : undefined,
};
}

export async function fetchBooks(signal: AbortSignal): Promise<Book[]> {
const response = await fetch(SEARCH_URL, { signal });
if (!response.ok) {
throw new Error(response.status === 429
? 'The book service is busy. Wait a little before retrying.'
: `Could not load books (HTTP ${response.status}). Please try again.`);
}

const data: unknown = await response.json();
if (!isObject(data) || !Array.isArray(data.docs)) {
throw new Error('The book service returned an unexpected response.');
}

return data.docs.map((value: unknown): Book => {
const doc = readDocument(value);
return {
id: doc.key.replace('/works/', ''),
title: doc.title?.trim() || 'Untitled book',
author: doc.author_name?.map(name => name.trim()).join(', ') || 'Unknown author',
firstPublishYear: doc.first_publish_year,
};
});
}

2. Extend the provider with local additions​

loadBooks now writes only remoteBooks. The two source arrays are combined during rendering, and the existing read-status map works for both. Generate the ID outside the state updater so the updater remains pure. The form supplies validated, trimmed values to addBook.

src/state/BooksProvider.tsx
import { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { fetchBooks } from '../data/books';
import type { Book } from '../data/books';

type Phase = 'loading' | 'refreshing' | 'idle';
type BooksValue = {
books: Book[];
readById: Record<string, boolean>;
phase: Phase;
hasLoaded: boolean;
error: string | null;
loadBooks: (refresh?: boolean) => Promise<void>;
toggleRead: (id: string) => void;
addBook: (title: string, author: string, notes: string) => void;
};

const BooksContext = createContext<BooksValue | null>(null);

export function BooksProvider({ children }: { children: ReactNode }) {
const [remoteBooks, setRemoteBooks] = useState<Book[]>([]);
const [localBooks, setLocalBooks] = useState<Book[]>([]);
const books = [...localBooks, ...remoteBooks];
const nextLocalId = useRef(0);
const [readById, setReadById] = useState<Record<string, boolean>>({});
const [phase, setPhase] = useState<Phase>('loading');
const [hasLoaded, setHasLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const activeRequest = useRef<AbortController | null>(null);

const loadBooks = useCallback(async (refresh = false) => {
if (activeRequest.current) return;
const controller = new AbortController();
activeRequest.current = controller;
setPhase(refresh ? 'refreshing' : 'loading');
setError(null);

try {
// Space occasional attempts; do not hammer a public service.
await new Promise<void>(resolve => setTimeout(resolve, 1100));
if (controller.signal.aborted) return;
const nextBooks = await fetchBooks(controller.signal);
if (controller.signal.aborted) return;
setRemoteBooks(nextBooks);
setHasLoaded(true);
} catch (cause) {
if (controller.signal.aborted) return;
setError(cause instanceof Error ? cause.message : 'Could not load books. Please try again.');
} finally {
if (!controller.signal.aborted) {
activeRequest.current = null;
setPhase('idle');
}
}
}, []);

useEffect(() => {
void loadBooks();
return () => {
activeRequest.current?.abort();
activeRequest.current = null;
};
}, [loadBooks]);

function addBook(title: string, author: string, notes: string) {
nextLocalId.current += 1;
const id = `local-${Date.now()}-${nextLocalId.current}`;
const newBook: Book = { id, title, author, notes: notes || undefined };
setLocalBooks(previous => [newBook, ...previous]);
setReadById(previous => ({ ...previous, [id]: false }));
}

function toggleRead(id: string) {
setReadById(previous => ({ ...previous, [id]: !previous[id] }));
}

return (
<BooksContext.Provider value={{ books, readById, phase, hasLoaded, error, loadBooks, toggleRead, addBook }}>
{children}
</BooksContext.Provider>
);
}

export function useBooks() {
const value = useContext(BooksContext);
if (value === null) throw new Error('useBooks must be inside BooksProvider.');
return value;
}

The existing cancellation guard, delay between attempts, Retry, and refresh behavior remain. A response arriving while someone adds a book changes only the remote array, so it cannot overwrite that new entry. The counter lives above the routes and does not reset every time Add Book opens.

3. Name the three stack screens​

src/app/_layout.tsx
import { Stack } from 'expo-router';
import { BooksProvider } from '../state/BooksProvider';

export default function RootLayout() {
return (
<BooksProvider>
<Stack>
<Stack.Screen name="index" options={{ title: 'Reading List' }} />
<Stack.Screen name="books/add" options={{ title: 'Add Book' }} />
<Stack.Screen name="books/[id]" options={{ title: 'Book Details' }} />
</Stack>
</BooksProvider>
);
}

4. Keep the reusable book card​

This is the same card as Guide 09. It receives the combined collection’s metadata and the shared read status. Opening Details and toggling status are still separate actions.

src/components/BookCard.tsx
import { Pressable, StyleSheet, Text, View } from 'react-native';

type BookCardProps = {
title: string;
author: string;
isRead: boolean;
onToggleRead: () => void;
onOpenDetails: () => void;
};

export default function BookCard({ title, author, isRead, onToggleRead, onOpenDetails }: BookCardProps) {
const buttonLabel = isRead ? 'Mark as unread' : 'Mark as read';

return (
<View style={styles.card}>
<Pressable
style={({ pressed }) => [styles.bookRow, pressed && styles.detailsPressed]}
onPress={onOpenDetails}
accessibilityRole="button"
accessibilityLabel={'View details: ' + title}
>
<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>
<Text style={styles.detailsLink}>View details →</Text>
</View>
</Pressable>
<Text style={[styles.status, isRead && styles.readStatus]}>
Status: {isRead ? 'Read' : 'Unread'}
</Text>
<Pressable
style={({ pressed }) => [styles.button, pressed && styles.buttonPressed]}
onPress={onToggleRead}
accessibilityRole="button"
accessibilityLabel={buttonLabel + ': ' + title}
>
<Text style={styles.buttonText}>{buttonLabel}</Text>
</Pressable>
</View>
);
}

const styles = StyleSheet.create({
card: {
padding: 16,
gap: 12,
backgroundColor: '#ffffff',
borderWidth: 1,
borderColor: '#cbd5e1',
borderRadius: 16,
},
detailsPressed: { opacity: 0.7 },
detailsLink: { color: '#1e40af', fontSize: 16, fontWeight: '600' },
bookRow: { minHeight: 48, 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' },
});

5. Open the form from Reading List​

Add Book stays available during loading and failures. A local entry can appear immediately while the remote indicator is still visible; the indicator now explicitly says it concerns remote books. The derived progress count includes both sources. Pull-to-refresh and the accessible Refresh button remain.

src/app/index.tsx
import { useRouter } from 'expo-router';
import { ActivityIndicator, FlatList, Pressable, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import BookCard from '../components/BookCard';
import { useBooks } from '../state/BooksProvider';

export default function HomeScreen() {
const router = useRouter();
const { books, readById, phase, hasLoaded, error, loadBooks, toggleRead } = useBooks();
const busy = phase !== 'idle';
const completedCount = books.filter(book => readById[book.id]).length;
const progressPercent = books.length === 0 ? 0 : completedCount / books.length * 100;

return (
<SafeAreaView style={styles.screen} edges={['left', 'right', 'bottom']}>
<FlatList
data={books}
extraData={readById}
keyExtractor={book => book.id}
refreshing={phase === 'refreshing'}
onRefresh={() => { if (hasLoaded) void loadBooks(true); }}
alwaysBounceVertical
contentContainerStyle={styles.content}
renderItem={({ item }) => (
<BookCard
title={item.title}
author={item.author}
isRead={readById[item.id] ?? false}
onToggleRead={() => toggleRead(item.id)}
onOpenDetails={() => router.push({
pathname: '/books/[id]',
params: { id: item.id },
})}
/>
)}
ListHeaderComponent={
<View style={styles.header}>
<Text style={styles.heading} accessibilityRole="header">My Reading List</Text>
<Text style={styles.body}>Your books and Open Library results</Text>
<Pressable
onPress={() => router.push('/books/add')}
accessibilityRole="button"
accessibilityLabel="Open Add Book form"
style={({ pressed }) => [styles.button, pressed && styles.dimmed]}
>
<Text style={styles.buttonText}>Add Book</Text>
</Pressable>
{(hasLoaded || books.length > 0) && (
<>
<Text style={styles.body}>{completedCount} of {books.length} books read</Text>
<View
style={styles.progressTrack}
accessible
accessibilityRole="progressbar"
accessibilityLabel="Reading progress"
accessibilityValue={{ min: 0, max: 100, now: Math.round(progressPercent),
text: `${completedCount} of ${books.length} books read` }}
>
<View style={[styles.progressFill, { width: `${progressPercent}%` }]} />
</View>
</>
)}
{phase === 'loading' && (
<View style={styles.notice}>
<ActivityIndicator size="large" color="#1e40af" accessibilityLabel="Loading books" />
<Text style={styles.body} accessibilityLiveRegion="polite">Loading remote books…</Text>
</View>
)}
{phase === 'refreshing' && (
<Text style={styles.body} accessibilityLiveRegion="polite">Refreshing remote books…</Text>
)}
{error !== null && (
<View style={styles.notice}>
<Text style={styles.error} accessibilityRole="alert" accessibilityLiveRegion="polite">
{hasLoaded ? 'Could not refresh remote books. Keeping your list. ' : 'Remote books are unavailable. You can still add a book. '}{error}
</Text>
<Pressable
onPress={() => { void loadBooks(hasLoaded); }}
disabled={busy}
accessibilityRole="button"
accessibilityLabel="Retry loading books"
accessibilityState={{ disabled: busy }}
style={({ pressed }) => [styles.button, (pressed || busy) && styles.dimmed]}
>
<Text style={styles.buttonText}>Retry loading books</Text>
</Pressable>
</View>
)}
{hasLoaded && error === null && (
<Pressable
onPress={() => { void loadBooks(true); }}
disabled={busy}
accessibilityRole="button"
accessibilityLabel="Refresh books"
accessibilityState={{ disabled: busy }}
style={({ pressed }) => [styles.button, (pressed || busy) && styles.dimmed]}
>
<Text style={styles.buttonText}>Refresh books</Text>
</Pressable>
)}
</View>
}
ItemSeparatorComponent={() => <View style={styles.separator} />}
ListEmptyComponent={hasLoaded && error === null && phase === 'idle' ? (
<View style={styles.notice}>
<Text style={styles.bookTitle}>No books found</Text>
<Text style={styles.body}>No remote matches yet. Use Add Book to create your own entry.</Text>
</View>
) : null}
/>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#f1f5f9' },
content: { padding: 16, flexGrow: 1 },
header: { gap: 12, marginBottom: 20 },
heading: { color: '#0f172a', fontSize: 28, fontWeight: '700' },
body: { color: '#334155', fontSize: 16 },
bookTitle: { color: '#0f172a', fontSize: 20, fontWeight: '600' },
error: { color: '#991b1b', fontSize: 16 },
notice: { padding: 16, gap: 12, backgroundColor: '#ffffff', borderRadius: 16 },
separator: { height: 16 },
progressTrack: { height: 12, borderRadius: 6, backgroundColor: '#cbd5e1', overflow: 'hidden' },
progressFill: { height: '100%', backgroundColor: '#1e40af' },
button: { minHeight: 48, padding: 12, alignItems: 'center', justifyContent: 'center',
backgroundColor: '#1e40af', borderRadius: 10 },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', textAlign: 'center' },
dimmed: { opacity: 0.65 },
});

6. Build the Add Book screen​

submitBehavior="submit" lets Next invoke onSubmitEditing without first blurring the field. The handler focuses the next input. For notes, submitBehavior="newline" preserves multiline editing. autoCapitalize is a keyboard suggestion, not a transformation or validation rule. Refs here point to inputs or guard duplicate submission; the three editable strings remain ordinary state.

src/app/books/add.tsx
import { useRef, useState } from 'react';
import { useRouter } from 'expo-router';
import { useHeaderHeight } from 'expo-router/react-navigation';
import {
Keyboard, KeyboardAvoidingView, Platform, Pressable,
ScrollView, StyleSheet, Text, TextInput, View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useBooks } from '../../state/BooksProvider';

export default function AddBookScreen() {
const router = useRouter();
const headerHeight = useHeaderHeight();
const { addBook } = useBooks();
const [title, setTitle] = useState('');
const [author, setAuthor] = useState('');
const [notes, setNotes] = useState('');
const [attempted, setAttempted] = useState(false);
const titleInput = useRef<TextInput>(null);
const authorInput = useRef<TextInput>(null);
const notesInput = useRef<TextInput>(null);
const submitted = useRef(false);

const titleError = attempted && title.trim().length === 0 ? 'Enter a book title.' : '';
const authorError = attempted && author.trim().length === 0 ? 'Enter an author name.' : '';

function handleSubmit() {
if (submitted.current) return;
setAttempted(true);
const cleanTitle = title.trim();
const cleanAuthor = author.trim();
if (!cleanTitle || !cleanAuthor) {
if (!cleanTitle) titleInput.current?.focus();
else authorInput.current?.focus();
return;
}

// Guard rapid double taps before navigation removes this screen.
submitted.current = true;
addBook(cleanTitle, cleanAuthor, notes.trim());
Keyboard.dismiss();
router.dismissTo('/');
}

function cancel() {
Keyboard.dismiss();
router.dismissTo('/');
}

return (
<SafeAreaView style={styles.screen} edges={['left', 'right', 'bottom']}>
<KeyboardAvoidingView
style={styles.flex}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
keyboardVerticalOffset={headerHeight}
>
<ScrollView
contentContainerStyle={styles.content}
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
>
<Text style={styles.heading} accessibilityRole="header">Add to your Reading List</Text>
<Text style={styles.body}>Title and author are required. Notes are optional.</Text>
<View style={styles.field}>
<Text style={styles.label}>Book title (required)</Text>
<TextInput
ref={titleInput}
value={title}
onChangeText={setTitle}
placeholder="Book title"
placeholderTextColor="#64748b"
accessibilityLabel="Book title, required"
accessibilityHint={titleError || 'Enter the title of the book.'}
autoCapitalize="words"
returnKeyType="next"
submitBehavior="submit"
onSubmitEditing={() => authorInput.current?.focus()}
style={[styles.input, titleError !== '' && styles.invalid]}
/>
{titleError !== '' && (
<Text style={styles.error} accessibilityRole="alert" accessibilityLiveRegion="polite">
{titleError}
</Text>
)}
</View>
<View style={styles.field}>
<Text style={styles.label}>Author (required)</Text>
<TextInput
ref={authorInput}
value={author}
onChangeText={setAuthor}
placeholder="Author name"
placeholderTextColor="#64748b"
accessibilityLabel="Author, required"
accessibilityHint={authorError || 'Enter the author name.'}
autoCapitalize="words"
returnKeyType="next"
submitBehavior="submit"
onSubmitEditing={() => notesInput.current?.focus()}
style={[styles.input, authorError !== '' && styles.invalid]}
/>
{authorError !== '' && (
<Text style={styles.error} accessibilityRole="alert" accessibilityLiveRegion="polite">
{authorError}
</Text>
)}
</View>
<View style={styles.field}>
<Text style={styles.label}>Notes (optional)</Text>
<TextInput
ref={notesInput}
value={notes}
onChangeText={setNotes}
placeholder="What would you like to remember?"
placeholderTextColor="#64748b"
accessibilityLabel="Notes, optional"
multiline
autoCapitalize="sentences"
returnKeyType="default"
submitBehavior="newline"
style={[styles.input, styles.notes]}
/>
</View>
<Text style={styles.body}>Books and notes stay in memory until the app restarts.</Text>
<Pressable
onPress={Keyboard.dismiss}
accessibilityRole="button"
accessibilityLabel="Hide keyboard"
style={({ pressed }) => [styles.secondaryButton, pressed && styles.pressed]}
>
<Text style={styles.secondaryText}>Hide keyboard</Text>
</Pressable>
<Pressable
onPress={handleSubmit}
accessibilityRole="button"
accessibilityLabel="Add Book"
style={({ pressed }) => [styles.button, pressed && styles.pressed]}
>
<Text style={styles.buttonText}>Add Book</Text>
</Pressable>
<Pressable
onPress={cancel}
accessibilityRole="button"
accessibilityLabel="Cancel adding a book"
style={({ pressed }) => [styles.secondaryButton, pressed && styles.pressed]}
>
<Text style={styles.secondaryText}>Cancel</Text>
</Pressable>
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#f1f5f9' },
flex: { flex: 1 },
content: { padding: 16, gap: 16, flexGrow: 1 },
heading: { color: '#0f172a', fontSize: 26, fontWeight: '700' },
body: { color: '#334155', fontSize: 16 },
field: { gap: 8 },
label: { color: '#0f172a', fontSize: 16, fontWeight: '600' },
input: { minHeight: 48, padding: 12, borderWidth: 1, borderColor: '#64748b',
borderRadius: 10, backgroundColor: '#ffffff', color: '#0f172a', fontSize: 18 },
notes: { minHeight: 120, textAlignVertical: 'top' },
invalid: { borderColor: '#991b1b', borderWidth: 2 },
error: { color: '#991b1b', fontSize: 16 },
button: { minHeight: 48, padding: 12, borderRadius: 10, backgroundColor: '#1e40af',
alignItems: 'center', justifyContent: 'center' },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600' },
secondaryButton: { minHeight: 48, padding: 12, alignItems: 'center', justifyContent: 'center' },
secondaryText: { color: '#1e40af', fontSize: 16, fontWeight: '600' },
pressed: { opacity: 0.65 },
});

The submission handler checks the trimmed values directly. It does not read error messages immediately after setAttempted, because that setter schedules the next render. A successful handler queues the shared-state updates before navigating; there is no server response to await. The submitted ref prevents rapid repeated presses from saving twice during the transition.

7. Resolve either kind of book on Details​

Look up any single string ID in the combined collection. We retain the Open Library ID check only to decide whether a missing remote book might still be loading. A missing local entry cannot be recovered by retrying the API, so it shows the fallback immediately. Missing or array-shaped parameters also fall back safely.

src/app/books/[id].tsx
import { useLocalSearchParams, useRouter } from 'expo-router';
import { ActivityIndicator, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useBooks } from '../../state/BooksProvider';

export default function BookDetailsScreen() {
const { id } = useLocalSearchParams<{ id?: string | string[] }>();
const router = useRouter();
const { books, readById, phase, hasLoaded, error, loadBooks } = useBooks();
const isRemoteId = typeof id === 'string' && /^OL\d+W$/.test(id);
const book = typeof id === 'string'
? books.find(candidate => candidate.id === id) : undefined;
const busy = phase !== 'idle';

function returnToReadingList() {
router.dismissTo('/');
}

return (
<SafeAreaView style={styles.screen} edges={['left', 'right', 'bottom']}>
<ScrollView contentContainerStyle={styles.content}>
<View style={styles.card}>
{book ? (
<>
<Text style={styles.heading} accessibilityRole="header">{book.title}</Text>
<Text style={styles.author}>{book.author}</Text>
<Text style={styles.body}>Status: {readById[book.id] ? 'Read' : 'Unread'}</Text>
{book.notes ? (
<>
<Text style={styles.body} accessibilityRole="header">Notes</Text>
<Text style={styles.body}>{book.notes}</Text>
</>
) : null}
<Text style={styles.body}>Return to your Reading List to change reading progress.</Text>
</>
) : isRemoteId && busy ? (
<>
<ActivityIndicator size="large" color="#1e40af" accessibilityLabel="Loading books" />
<Text style={styles.body} accessibilityLiveRegion="polite">Loading books…</Text>
</>
) : isRemoteId && error !== null ? (
<>
<Text style={styles.body} accessibilityRole="alert">{error}</Text>
<Pressable
onPress={() => { void loadBooks(hasLoaded); }}
accessibilityRole="button"
accessibilityLabel="Retry loading books"
style={({ pressed }) => [styles.button, pressed && styles.dimmed]}
>
<Text style={styles.buttonText}>Retry loading books</Text>
</Pressable>
</>
) : (
<>
<Text style={styles.heading} accessibilityRole="header">Book not found</Text>
<Text style={styles.body}>Choose a book from your current Reading List. Local entries disappear after a restart.</Text>
</>
)}
<Pressable
onPress={returnToReadingList}
accessibilityRole="button"
accessibilityLabel="Return to Reading List"
style={({ pressed }) => [styles.button, pressed && styles.dimmed]}
>
<Text style={styles.buttonText}>Return to Reading List</Text>
</Pressable>
</View>
</ScrollView>
</SafeAreaView>
);
}

const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#f1f5f9' },
content: { padding: 16 },
card: { padding: 16, gap: 12, backgroundColor: '#ffffff', borderWidth: 1,
borderColor: '#cbd5e1', borderRadius: 16 },
heading: { color: '#0f172a', fontSize: 28, fontWeight: '700' },
author: { color: '#475569', fontSize: 20 },
body: { color: '#334155', fontSize: 16 },
button: { minHeight: 48, padding: 12, alignItems: 'center', justifyContent: 'center',
backgroundColor: '#1e40af', borderRadius: 10 },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', textAlign: 'center' },
dimmed: { opacity: 0.65 },
});

Check the expected screen and behavior​

Run npx expo start in the learning app. Open Reading List and select Add Book. Expect the normal Add Book stack header, a title field, an author field, a taller optional notes field, and Hide keyboard, Add Book, and Cancel controls. Required labels remain visible after typing. Empty submission shows “Enter a book title” and “Enter an author name” beside the relevant fields. This describes the intended UI, not a simulator screenshot.

The website build validates MDX and site links; it does not execute the app example. Use this manual walkthrough on iOS and Android, then check direct routes with Expo web:

ActionExpected result
Open /books/add directly in the Expo web previewThe form and Add Book header appear, not Book Details or “Book not found”.
Submit empty fields or spaces onlyHelpful messages; no book is added; first invalid input receives focus.
Fix title while leaving author emptyTitle error disappears, author error remains.
Enter My Book and A Reader , leave notes empty, and submitReading List shows “My Book” by “A Reader” at the top, unread.
Add notes with line breaks and open DetailsNotes and metadata match the saved entry.
Tap Add Book rapidly during successful submissionOne entry is added, not duplicate copies.
Mark the new entry read, open Details, and returnStatus and progress remain consistent.
Refresh remote books, including while adding an entryLocal books, notes, and statuses remain. Remote results can change.
Disable connectivity and add a local bookAddition and local Details still work; the remote request may show its own error.
Open a known remote ID, then an unknown IDRemote Details still works; the unknown ID has a readable fallback.
Press Next through title and author; Return in notesFocus advances, then Return inserts a newline without saving.
Use a small screen, larger text, and the software keyboardScroll to every field and action without keyboard overlap.
Cancel or use the header Back before savingThe draft is discarded when the form unmounts; the list does not gain an entry.
Fully restart/reload after savingLocal entries and read status reset; remote books load again.

Use VoiceOver or TalkBack to check field names, required/optional hints, errors, and button labels. Verify the first button tap while the keyboard is open, and check Android’s back-to-dismiss behavior. A desktop browser with no software keyboard cannot verify native keyboard avoidance.

If /books/add unexpectedly shows Details, check the exact add.tsx filename, its default export, the single src/app route root, and conflicting template routes. Restart Metro after creating the route file. Do not special-case id === 'add' inside Details.

Fix common mistakes​

MistakeCorrection
Using defaultValue for this controlled formUse value with state; defaultValue only supplies an initial uncontrolled value.
Supplying value but forgetting onChangeTextUpdate the corresponding state string or edits cannot be retained.
Expecting inputs to update the Reading List automaticallyTyping edits draft state. Call the shared addBook action on valid submission.
Accepting spaces as a titleCheck the trimmed string’s length before saving.
Navigating away before savingQueue the provider update first, then dismiss to Reading List.
Using array indices, timestamps alone, or IDs generated during renderingGenerate once when adding; use the local prefix and provider counter.
Losing local books after refreshReplace only remoteBooks; derive the combined collection from both sources.
Rejecting local IDs in DetailsLook up the combined books; reserve the remote-ID check for remote loading/retry UI.
Errors remain after a field is fixedDerive errors from the current text after a submission attempt.
The keyboard covers the submit buttonCheck the header offset, scrollable content, and platform behavior on a device.
Expecting books to survive an app restartThis lesson stores data in memory; navigation is not persistence.

Understand what survives navigation​

The provider stays above all three screens. Pushing Add Book or Details and returning does not recreate it, so saved entries remain during that navigation. Draft text belongs to the form and is discarded when that screen unmounts. Cancel does not save a draft.

A full app restart, reload, or provider remount recreates its state. Locally added books, notes, and read status then disappear. Development Fast Refresh can sometimes preserve state, so use a full reload when checking this limitation. A saved local Details URL will not restore a lost entry, and the remote API has no copy of it.

The next lesson, Local Data Persistence, adds saving across restarts. This lesson keeps additions in memory. Form libraries such as React Hook Form and Formik exist for more complex forms, but three explicit state values and simple validation are enough here.

Practice​

  1. Optional category. Add a category input, include it in the local entry, and display it on Details. Keep remote books without a category readable.
  2. Notes counter. Show the current number of characters beneath notes. Derive it from the text rather than storing a second count.
  3. Confirmation message. Show a brief, accessible success message on Reading List after adding a book. Decide which shared state must outlive the form and when the message should clear.

Check your understanding​

  1. How do value and onChangeText work together?
  2. Why should typing not call addBook?
  3. Why is " " an invalid title even though its length is greater than zero?
  4. Why does the provider own saved entries while the form owns draft strings?
  5. Why does refreshing remote results preserve local books?
  6. How do the prefix and counter prevent ID collisions in this example?
  7. Why can a local book survive Back navigation but disappear after restarting?
Compare your answers

State supplies the displayed input value, and the change callback updates that state. Typing changes an unfinished draft; only submission validates and saves one entry. Trimming removes whitespace-only content. The provider outlives individual screens and is available to Home and Details. Refresh writes only the remote array; the local array and shared status map remain. The prefix separates local from API IDs, and the increasing counter distinguishes additions within the provider’s lifetime. Navigation keeps the provider mounted, whereas restarting creates fresh in-memory state.

You are ready to continue when: You can add a valid book, correct invalid input, open its details, and refresh remote results without losing the local entry.

Next: Local Data Persistence, or return to the learning path. Editing, deletion, draft recovery, advanced validation, and server writes are outside this lesson.

Official references​