Mobile development · Intermediate · 28 min
Build the Larkfield booking form with React Hook Form and Zod
By Padding · Updated 18 Nov 2026
Expo SDK 58 · React Native 0.88 · React Hook Form 7.92 · Zod 4.6 · Node.js 26 (node:26 image)
You will have a tested booking details screen in the Larkfield Clinic Expo app that validates name, mobile number, date of birth and reason with one shared Zod schema, moves focus field to field, announces errors to screen readers and cannot be submitted twice.
On this page
In part 1 you built the shell of the Larkfield Clinic app: tabs for Book, Appointments and Profile, and a Book stack where a patient picks a service, a practitioner and a time. The next screen asks who the patient is. It is short, four fields, but it is where most booking apps lose people: the wrong keyboard opens, an error appears with no explanation, the button hides behind the keyboard, or a slow connection and a second tap send the request twice.
You will build that screen with React Hook Form, which re-renders only the field that changes rather than the whole form, and Zod, which describes what valid data looks like. The rules live in one plain TypeScript module with no React Native imports, so the same schema can check requests in the mock clinic API later in the series. Every rule has a Jest test, and a React Native Testing Library test fills in the form the way a patient would.
The form follows the decisions from designing a mobile form people can finish: one column, labels above fields, the right keyboard for each field and one clear button.
Step 1 · Add React Hook Form, Zod and the resolver
Three packages do the work. react-hook-form holds the values, errors and submit state. zod defines the schema. @hookform/resolvers connects the two, so React Hook Form asks Zod whether the values are valid. All three are plain JavaScript with no native code, so npm installs them directly and no new development build is needed. The versions are pinned so the code below behaves exactly as described:
cd ~/larkfield-app-demo
npm install react-hook-form@7.92.0 zod@4.6.7 @hookform/resolvers@7.0.9
mkdir -p src/shared src/components src/bookingsrc/shared holds code with no React Native imports, which a Node server can also load. src/components holds the form, and src/booking holds the place a finished request goes.
Check it worked
npm ls react-hook-form zod @hookform/resolversThe tree lists react-hook-form@7.92.0, zod@4.6.7 and @hookform/resolvers@7.0.9, with no UNMET PEER DEPENDENCY lines.
Step 2 · Write the phone number rules and test them
Larkfield takes bookings from patients in Nigeria and Kenya, and the clinic texts them to confirm. People type numbers in many shapes: 0803 123 4567, +234 803 123 4567, 0712-345-678. The app accepts all of them and stores one form, the international E.164 format (+2348031234567), so a text message gateway can use it as it is.
The rules, from each country's numbering plan:
- Nigeria (
+234): mobile numbers have 10 digits after the country code and start with 70, 80, 81, 90 or 91. Written locally they start with0, so 11 digits. - Kenya (
+254): mobile numbers have 9 digits after the country code and start with 7 or 1 (the newer 01 range). Locally, 10 digits starting07or01.
The two local lengths differ, so a number that starts with 0 belongs to one country only. Create src/shared/phone.ts:
cat > src/shared/phone.ts <<'TS'
type Rule = { country: 'NG' | 'KE'; code: string; national: RegExp }
const RULES: Rule[] = [
{ country: 'NG', code: '234', national: /^[789][01]\d{8}$/ },
{ country: 'KE', code: '254', national: /^[17]\d{8}$/ },
]
// Returns the number in E.164 form (+2348031234567), or null if it is not
// a Nigerian or Kenyan mobile number.
export function normalisePhone(input: string): string | null {
const compact = input.replace(/[\s().-]/g, '')
for (const rule of RULES) {
let national: string | null = null
if (compact.startsWith(`+${rule.code}`)) national = compact.slice(rule.code.length + 1)
else if (compact.startsWith(`00${rule.code}`)) national = compact.slice(rule.code.length + 2)
else if (compact.startsWith('0')) national = compact.slice(1)
if (national !== null && rule.national.test(national)) return `+${rule.code}${national}`
}
return null
}
TSSpaces, dashes, dots and brackets are removed first, then the number is matched with a + prefix, a 00 international prefix, or the local 0. Supporting another country later means adding one line to RULES and a test.
Now the tests. Jest finds any file ending in .test.ts:
cat > src/shared/phone.test.ts <<'TS'
import { normalisePhone } from './phone'
test.each([
['0803 123 4567', '+2348031234567'],
['+234 803 123 4567', '+2348031234567'],
['00234-909-123-4567', '+2349091234567'],
['0712 345 678', '+254712345678'],
['+254 (110) 123 456', '+254110123456'],
])('accepts %s as %s', (input, expected) => {
expect(normalisePhone(input)).toBe(expected)
})
test.each(['', '12345', '0201234567', '+234 603 123 4567', '+44 7700 900123'])(
'rejects %p',
(input) => {
expect(normalisePhone(input)).toBeNull()
},
)
TS
npx jest src/shared/phone.test.tsCheck it worked
Jest reports Tests: 10 passed, 10 total. Change [789][01] to [78][01] in phone.ts, run the same command again and the 00234-909-123-4567 case fails, which proves the tests check the rule rather than just running. Put the rule back.
Step 3 · Describe a valid booking with one Zod schema
The schema is the single description of a valid booking. It decides the error message for each field, and it turns what the patient typed (the input) into what the app stores (the output): trimmed text and a normalised phone number.
Two choices keep the messages clean. Each field reports one problem at a time, in the order a patient would fix them (empty, then the wrong format, then out of range), so a field never shows two errors at once. Names accept any letters: Larkfield's patients write names such as Ngozi Ọkọnkwọ and Wanjikũ, and a rule that only allows A to Z rejects them.
Create src/shared/booking.ts:
cat > src/shared/booking.ts <<'TS'
import { z } from 'zod'
import { normalisePhone } from './phone'
export const PHONE_HINT = 'Nigerian or Kenyan mobile, for example 0803 123 4567 or 0712 345 678'
// Today's date as YYYY-MM-DD in the phone's own time zone.
export function todayIso(now = new Date()): string {
const month = String(now.getMonth() + 1).padStart(2, '0')
const day = String(now.getDate()).padStart(2, '0')
return `${now.getFullYear()}-${month}-${day}`
}
function isRealIsoDate(value: string): boolean {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false
const [year, month, day] = value.split('-').map(Number)
const date = new Date(Date.UTC(year, month - 1, day))
return (
date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
)
}
export const bookingSchema = z.object({
fullName: z
.string()
.trim()
.min(2, 'Enter your full name')
.max(80, 'Keep your name under 80 characters'),
phone: z.string().transform((value, ctx) => {
if (value.trim() === '') {
ctx.addIssue({ code: 'custom', message: 'Enter your mobile number' })
return z.NEVER
}
const e164 = normalisePhone(value)
if (!e164) {
ctx.addIssue({ code: 'custom', message: `Enter a ${PHONE_HINT}` })
return z.NEVER
}
return e164
}),
dateOfBirth: z
.string()
.trim()
.superRefine((value, ctx) => {
if (value === '') {
ctx.addIssue({ code: 'custom', message: 'Enter your date of birth' })
} else if (!isRealIsoDate(value)) {
ctx.addIssue({ code: 'custom', message: 'Enter a real date as YYYY-MM-DD, for example 1990-04-23' })
} else if (value > todayIso()) {
ctx.addIssue({ code: 'custom', message: 'Date of birth cannot be in the future' })
} else if (value < '1900-01-01') {
ctx.addIssue({ code: 'custom', message: 'Check the year of your date of birth' })
}
}),
reason: z
.string()
.trim()
.min(5, 'Tell us in a few words why you are coming')
.max(300, 'Keep the reason under 300 characters'),
})
// What the form holds while the patient types.
export type BookingFormValues = z.input<typeof bookingSchema>
// What the app stores and sends: trimmed, with the phone in E.164 form.
export type BookingRequest = z.output<typeof bookingSchema>
TSz.NEVER tells Zod that the transform failed and the value should not be used. ISO dates compare correctly as strings ('1990-04-23' < '2026-11-18'), so the future check needs no date library. BookingRequest is the type the API will accept, inferred from the schema, so the two cannot drift apart.
Test the schema:
cat > src/shared/booking.test.ts <<'TS'
import { bookingSchema } from './booking'
const valid = {
fullName: ' Amina Yusuf ',
phone: '0803 123 4567',
dateOfBirth: '1990-04-23',
reason: 'Follow-up on my blood pressure',
}
function messagesFor(values: Record<string, string>) {
const result = bookingSchema.safeParse(values)
if (result.success) return {}
return Object.fromEntries(result.error.issues.map((issue) => [issue.path[0], issue.message]))
}
test('turns valid input into a clean booking request', () => {
expect(bookingSchema.parse(valid)).toEqual({
fullName: 'Amina Yusuf',
phone: '+2348031234567',
dateOfBirth: '1990-04-23',
reason: 'Follow-up on my blood pressure',
})
})
test('accepts names outside A to Z', () => {
expect(bookingSchema.safeParse({ ...valid, fullName: 'Ngozi Ọkọnkwọ' }).success).toBe(true)
expect(bookingSchema.safeParse({ ...valid, fullName: 'Wanjikũ Kamau' }).success).toBe(true)
})
test('gives one message per empty field', () => {
const result = bookingSchema.safeParse({ fullName: '', phone: '', dateOfBirth: '', reason: '' })
expect(result.success).toBe(false)
expect(result.error?.issues.map((issue) => issue.path[0])).toEqual([
'fullName',
'phone',
'dateOfBirth',
'reason',
])
})
test('rejects dates in the future, impossible dates and other formats', () => {
expect(messagesFor({ ...valid, dateOfBirth: '2999-01-01' }).dateOfBirth).toBe(
'Date of birth cannot be in the future',
)
expect(messagesFor({ ...valid, dateOfBirth: '1990-02-30' }).dateOfBirth).toMatch(/real date/)
expect(messagesFor({ ...valid, dateOfBirth: '23/04/1990' }).dateOfBirth).toMatch(/YYYY-MM-DD/)
expect(messagesFor({ ...valid, dateOfBirth: '1850-01-01' }).dateOfBirth).toMatch(/year/)
})
test('rejects a number from another country with a hint', () => {
expect(messagesFor({ ...valid, phone: '+44 7700 900123' }).phone).toMatch(/0803 123 4567/)
})
TS
npx jest src/sharedCheck it worked
Jest runs both files in src/shared and reports Tests: 15 passed, 15 total. If the empty-field test fails with an extra entry, a field is reporting two problems at once: check that each rule after the first is in an else if.
Step 4 · Build a field that shows its label, keyboard and error
Every field on the screen has the same parts: a visible label, the input, and a space under it for the error. Put them in one component so the four fields cannot drift apart.
Three accessibility details are built in. The input's accessibilityLabel matches the visible label, so a screen reader says "Mobile number" and not "text field". When there is an error, it becomes the input's accessibilityHint, which is read when the patient returns to the field. The error text sits in an accessibilityLiveRegion, so Android's TalkBack reads it out when it appears. The live region is always rendered, empty when there is no error, because Android only announces changes to a region that already exists. It also reserves the space, so the form does not jump when an error appears.
The form takes its colours from src/theme.ts, the same module part 1's headers and screens use, so the clinic's look still changes in one file. It needs two colours the theme does not have yet: a darker border for inputs, because the light line grey is too faint around a field a patient has to find, and a red for errors. Replace the file with part 1's values plus those two:
cat > src/theme.ts <<'TS'
export const colours = {
ink: '#0b0c0e',
text: '#2a2d33',
muted: '#6a707b',
line: '#d9dce1',
field: '#9ba1ac',
canvas: '#f1f2f4',
surface: '#ffffff',
accent: '#1d5c4d',
danger: '#b3261e',
}
export const headerOptions = {
headerStyle: { backgroundColor: colours.surface },
headerTintColor: colours.ink,
headerTitleStyle: { fontWeight: '600' as const },
headerShadowVisible: false,
}
TSIn React 19, ref is an ordinary prop for function components, so the field passes it straight to the TextInput with no forwardRef. React Hook Form needs that ref to move focus. Create src/components/FormField.tsx:
cat > src/components/FormField.tsx <<'TSX'
import type { Ref } from 'react'
import { StyleSheet, Text, TextInput, View, type TextInputProps } from 'react-native'
import { colours } from '@/theme'
type Props = TextInputProps & {
label: string
hint?: string
error?: string
ref?: Ref<TextInput>
}
export function FormField({ label, hint, error, ref, style, ...inputProps }: Props) {
return (
<View style={styles.field}>
<Text style={styles.label}>{label}</Text>
{hint ? <Text style={styles.hint}>{hint}</Text> : null}
<TextInput
ref={ref}
accessibilityLabel={label}
accessibilityHint={error ?? hint}
style={[styles.input, error ? styles.inputError : null, style]}
placeholderTextColor={colours.muted}
{...inputProps}
/>
<Text accessibilityLiveRegion="polite" style={styles.error}>
{error ?? ''}
</Text>
</View>
)
}
const styles = StyleSheet.create({
field: { gap: 4 },
label: { fontSize: 16, fontWeight: '600', color: colours.ink },
hint: { fontSize: 14, color: colours.muted },
input: {
minHeight: 48,
borderWidth: 1,
borderColor: colours.field,
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 10,
fontSize: 17,
color: colours.ink,
backgroundColor: colours.surface,
},
inputError: { borderColor: colours.danger, borderWidth: 2 },
error: { minHeight: 20, fontSize: 14, color: colours.danger },
})
TSXThe input is at least 48 points tall, a comfortable target on a small Android phone, and the error is shown by a thicker border as well as colour, so it does not depend on telling red from grey.
Check it worked
grep -c "accessibilityLiveRegion" src/components/FormField.tsx
grep -c "#" src/components/FormField.tsx || trueThe first command prints 1 and the second prints 0: every colour comes from the theme. The full behaviour is tested once the form exists, in the last step.
Step 5 · Wire the four fields to React Hook Form
Controller connects a field to the form. Its render function receives field (value, onChange, onBlur and ref) and fieldState (this field's error). Each TextInput gets the keyboard and autofill hints that suit it:
| Field | keyboardType | iOS textContentType | Android and web autoComplete |
|---|---|---|---|
| Full name | default | name | name |
| Mobile number | phone-pad | telephoneNumber | tel |
| Date of birth | numbers-and-punctuation (iOS only; Android shows its standard keyboard) | birthdate | birthdate-full |
| Reason | default, multiline | none | off |
Autofill matters more than it looks. On a cheap phone with a small screen, a patient who can fill name and number in one tap is far more likely to finish.
Focus moves to the next field when the patient presses the return key, which shows "Next" because of returnKeyType="next". setFocus('phone') from React Hook Form calls focus() on the ref that Controller registered, so you do not keep your own refs. submitBehavior="submit" keeps the keyboard open while focus moves. One limit: the iOS phone pad has no return key, so on iPhone the patient taps the date field. Android's phone keyboard has one.
The form validates a field when the patient leaves it (mode: 'onBlur'), not on every key, so nobody sees "Enter a real date" after typing the first digit. After a failed submit, fields re-validate as the patient types, so an error clears the moment it is fixed.
Create src/components/BookingForm.tsx. The submit button and the keyboard handling are explained in the next step:
cat > src/components/BookingForm.tsx <<'TSX'
import { zodResolver } from '@hookform/resolvers/zod'
import { useRef } from 'react'
import { Controller, useForm } from 'react-hook-form'
import {
AccessibilityInfo,
KeyboardAvoidingView,
Platform,
Pressable,
ScrollView,
StyleSheet,
Text,
} from 'react-native'
import { PHONE_HINT, bookingSchema, type BookingFormValues, type BookingRequest } from '../shared/booking'
import { colours } from '@/theme'
import { FormField } from './FormField'
const FIELD_LABELS: Record<keyof BookingFormValues, string> = {
fullName: 'Full name',
phone: 'Mobile number',
dateOfBirth: 'Date of birth',
reason: 'Reason for the visit',
}
type Props = {
onSubmit: (booking: BookingRequest) => Promise<void>
keyboardOffset?: number
}
export function BookingForm({ onSubmit, keyboardOffset = 0 }: Props) {
const {
control,
handleSubmit,
setFocus,
setError,
reset,
formState: { errors, isSubmitting },
} = useForm({
resolver: zodResolver(bookingSchema),
defaultValues: { fullName: '', phone: '', dateOfBirth: '', reason: '' },
mode: 'onBlur',
})
const sending = useRef(false)
const submit = handleSubmit(
async (booking) => {
if (sending.current) return
sending.current = true
try {
await onSubmit(booking)
reset()
} catch {
const message = 'Your request was not sent. Check your connection and try again.'
setError('root', { message })
AccessibilityInfo.announceForAccessibility(message)
} finally {
sending.current = false
}
},
(invalid) => {
const labels = Object.keys(invalid).map((name) => FIELD_LABELS[name as keyof BookingFormValues])
const count = labels.length === 1 ? '1 field' : `${labels.length} fields`
AccessibilityInfo.announceForAccessibility(`Check ${count}: ${labels.join(', ')}`)
},
)
return (
<KeyboardAvoidingView
style={styles.flex}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
keyboardVerticalOffset={keyboardOffset}
>
<ScrollView contentContainerStyle={styles.form} keyboardShouldPersistTaps="handled">
<Controller
control={control}
name="fullName"
render={({ field, fieldState }) => (
<FormField
ref={field.ref}
label="Full name"
value={field.value}
onChangeText={field.onChange}
onBlur={field.onBlur}
error={fieldState.error?.message}
autoCapitalize="words"
autoCorrect={false}
autoComplete="name"
textContentType="name"
returnKeyType="next"
submitBehavior="submit"
onSubmitEditing={() => setFocus('phone')}
/>
)}
/>
<Controller
control={control}
name="phone"
render={({ field, fieldState }) => (
<FormField
ref={field.ref}
label="Mobile number"
hint={PHONE_HINT}
value={field.value}
onChangeText={field.onChange}
onBlur={field.onBlur}
error={fieldState.error?.message}
keyboardType="phone-pad"
autoComplete="tel"
textContentType="telephoneNumber"
returnKeyType="next"
submitBehavior="submit"
onSubmitEditing={() => setFocus('dateOfBirth')}
/>
)}
/>
<Controller
control={control}
name="dateOfBirth"
render={({ field, fieldState }) => (
<FormField
ref={field.ref}
label="Date of birth"
hint="Year, month, day, for example 1990-04-23"
placeholder="YYYY-MM-DD"
value={field.value}
onChangeText={field.onChange}
onBlur={field.onBlur}
error={fieldState.error?.message}
keyboardType="numbers-and-punctuation"
autoComplete="birthdate-full"
textContentType="birthdate"
maxLength={10}
returnKeyType="next"
submitBehavior="submit"
onSubmitEditing={() => setFocus('reason')}
/>
)}
/>
<Controller
control={control}
name="reason"
render={({ field, fieldState }) => (
<FormField
ref={field.ref}
label="Reason for the visit"
value={field.value}
onChangeText={field.onChange}
onBlur={field.onBlur}
error={fieldState.error?.message}
multiline
maxLength={300}
autoComplete="off"
textAlignVertical="top"
style={styles.multiline}
/>
)}
/>
{errors.root ? (
<Text accessibilityLiveRegion="assertive" style={styles.rootError}>
{errors.root.message}
</Text>
) : null}
<Pressable
accessibilityRole="button"
accessibilityState={{ disabled: isSubmitting, busy: isSubmitting }}
disabled={isSubmitting}
onPress={() => submit()}
style={({ pressed }) => [styles.button, (pressed || isSubmitting) && styles.buttonDimmed]}
>
<Text style={styles.buttonText}>{isSubmitting ? 'Sending' : 'Request appointment'}</Text>
</Pressable>
</ScrollView>
</KeyboardAvoidingView>
)
}
const styles = StyleSheet.create({
flex: { flex: 1 },
form: { padding: 16, gap: 8 },
multiline: { minHeight: 96 },
rootError: { fontSize: 15, color: colours.danger },
button: {
minHeight: 52,
borderRadius: 8,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: colours.ink,
marginTop: 8,
},
buttonDimmed: { backgroundColor: colours.muted },
buttonText: { fontSize: 17, fontWeight: '600', color: colours.surface },
})
TSXzodResolver(bookingSchema) gives useForm its types: the form holds BookingFormValues, and the function passed to handleSubmit receives a BookingRequest, already trimmed and with the phone in E.164 form. The errors are read as formState: { errors, isSubmitting } at the top of the component. React Hook Form only tracks the parts of formState you read, so reading them here, not inside a callback, is what keeps them up to date.
Check it worked
grep -c "<Controller" src/components/BookingForm.tsxThe command prints 4, one Controller per field. On a phone the form appears in the next step.
Step 6 · Keep the button reachable and stop double submission
Look at three parts of the component you just wrote.
The keyboard. The fields sit in a ScrollView inside a KeyboardAvoidingView. When the keyboard opens, the view shrinks or adds padding by the keyboard's height, and the patient can scroll down to the button. On iOS, padding is the dependable behaviour; on Android with Expo's edge-to-edge layout, height is the starting point. keyboardVerticalOffset must equal the distance from the top of the screen to the top of the form, which on this screen is the stack header. keyboardShouldPersistTaps="handled" means a tap on the button while the keyboard is open presses the button straight away, instead of only closing the keyboard. If the keyboard still covers the button on one of your phones, Expo's keyboard guide describes react-native-keyboard-controller, which measures the keyboard more precisely on both platforms.
Errors on submit. handleSubmit takes a second function that runs when validation fails. React Hook Form has already moved focus to the first field with an error (its shouldFocusError option is on by default, and it uses the same refs as setFocus). The function then calls AccessibilityInfo.announceForAccessibility with a summary such as "Check 2 fields: Mobile number, Date of birth". That covers iOS VoiceOver, which ignores accessibilityLiveRegion.
One request, not two. While the async submit function runs, isSubmitting is true: the button is disabled, marked busy for screen readers, dimmed and labelled "Sending". On a slow mobile data connection that can be several seconds, which is exactly when people tap again. The sending ref is a second guard. State updates reach the screen on the next render, but a ref changes at once, so even two taps in the same frame send one request. If the request fails, the form keeps what the patient typed and shows a message above the button.
Check it worked
Read the component for each guard: disabled={isSubmitting} on the Pressable, if (sending.current) return at the top of the submit function, and setError('root', ...) in the catch. The last step proves each one with a test.
Step 7 · Put the form on the Book stack
The screen file goes in the Book stack from part 1, so its address is /book/details. For now a finished request is kept in memory. In part 3 the screen's submit handler saves to expo-sqlite instead, so requests survive closing the app, and the form itself does not change. Create src/booking/pending.ts:
cat > src/booking/pending.ts <<'TS'
import type { BookingRequest } from '../shared/booking'
export type PendingBooking = BookingRequest & { service?: string; time?: string }
const pending: PendingBooking[] = []
export async function saveBookingRequest(booking: PendingBooking): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 400))
pending.push(booking)
}
export function pendingBookings(): PendingBooking[] {
return [...pending]
}
TSThe 400 ms pause stands in for the network, so you can see the "Sending" state on the button. Now the screen. It reads the service and time from the route's parameters, if the previous screen passed them, and shows a confirmation after a request is saved:
cat > "src/app/(tabs)/book/details.tsx" <<'TSX'
import { Stack, useLocalSearchParams } from 'expo-router'
import { useState } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import { saveBookingRequest } from '@/booking/pending'
import { BookingForm } from '@/components/BookingForm'
import { colours } from '@/theme'
export default function BookingDetailsScreen() {
const { service, time } = useLocalSearchParams<{ service?: string; time?: string }>()
const [confirmedPhone, setConfirmedPhone] = useState<string | null>(null)
const summary = [service, time].filter(Boolean).join(' · ')
return (
<View style={styles.screen}>
<Stack.Screen options={{ title: 'Your details' }} />
{summary ? <Text style={styles.summary}>{summary}</Text> : null}
{confirmedPhone ? (
<Text accessibilityLiveRegion="polite" style={styles.done}>
Request saved. The clinic will text {confirmedPhone} to confirm.
</Text>
) : null}
<BookingForm
keyboardOffset={100}
onSubmit={async (booking) => {
await saveBookingRequest({ ...booking, service, time })
setConfirmedPhone(booking.phone)
}}
/>
</View>
)
}
const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: colours.canvas },
summary: { paddingHorizontal: 16, paddingTop: 16, fontSize: 15, color: colours.text },
done: { marginHorizontal: 16, marginTop: 12, fontSize: 15, color: colours.ink },
})
TSXkeyboardOffset={100} is a starting value for a stack header below the status bar. Adjust it when you try the form on your phones.
Now connect it. In part 1, tapping a time on src/app/(tabs)/book/[serviceId].tsx only showed "You chose ...". Make two changes to that file. Add router to the expo-router import, so the first line reads:
import { Stack, router, useLocalSearchParams } from 'expo-router'Then, on the time slot's Pressable, replace onPress={() => setChoice({ slot, practitioner: practitioner.name })} with a push to the new screen that passes what the patient chose:
onPress={() => router.push({ pathname: '/book/details', params: { service: service.name, time: slot.label } })}The choice state and the "You chose" line stay in the file but no longer change; delete them if you prefer. Or make both edits with this command, which stops with an error if the file does not match part 1:
cd ~/larkfield-app-demo
node -e "
const fs = require('fs')
const file = 'src/app/(tabs)/book/[serviceId].tsx'
const edits = [
[\"import { Stack, useLocalSearchParams } from 'expo-router'\", \"import { Stack, router, useLocalSearchParams } from 'expo-router'\"],
['onPress={() => setChoice({ slot, practitioner: practitioner.name })}', \"onPress={() => router.push({ pathname: '/book/details', params: { service: service.name, time: slot.label } })}\"],
]
let src = fs.readFileSync(file, 'utf8')
for (const [from, to] of edits) {
if (src.indexOf(from) === -1) throw new Error('Not found in ' + file + ': ' + from)
src = src.replace(from, to)
}
fs.writeFileSync(file, src)
"
grep -c "router.push" "src/app/(tabs)/book/[serviceId].tsx"The last command prints 1.
Start the app and try the form on a phone:
cd ~/larkfield-app-demo
npx expo startChoose General check-up and tap a time: the "Your details" screen opens with the service and time at the top. Tap through the fields with the return key, leave the date as 23/04/1990 to see the format error, and press the button twice quickly.
Check it worked
Without a phone, bundle every route for the web and check the form is in the bundle:
cd ~/larkfield-app-demo
npx expo export --platform web
grep -rl "Reason for the visit" dist > /dev/null && echo "booking form bundled"The export prints something like a list of bundles, one per route including book/details, and ends with Exported: dist. The last line prints booking form bundled.
Step 8 · Test the form the way a patient fills it in
React Native Testing Library renders the component in Jest and drives it like a person: userEvent.type focuses a field and types one character at a time, and userEvent.press taps. Queries find things the way a screen reader would, by label and by role. In version 14, render returns a promise, so each test awaits it.
The three tests match the three promises of the screen: errors appear under each field and are announced, a valid form sends one clean request, and a second tap while sending does nothing. Create src/components/BookingForm.test.tsx:
cat > src/components/BookingForm.test.tsx <<'TSX'
import { render, screen, userEvent, waitFor } from '@testing-library/react-native'
import { AccessibilityInfo } from 'react-native'
import { BookingForm } from './BookingForm'
async function fillValidForm(user: ReturnType<typeof userEvent.setup>) {
await user.type(screen.getByLabelText('Full name'), 'Amina Yusuf')
await user.type(screen.getByLabelText('Mobile number'), '0803 123 4567')
await user.type(screen.getByLabelText('Date of birth'), '1990-04-23')
await user.type(screen.getByLabelText('Reason for the visit'), 'Blood pressure check')
}
test('shows an error under each empty field and announces a summary', async () => {
const announce = jest
.spyOn(AccessibilityInfo, 'announceForAccessibility')
.mockImplementation(() => {})
const onSubmit = jest.fn()
const user = userEvent.setup()
await render(<BookingForm onSubmit={onSubmit} />)
await user.press(screen.getByRole('button', { name: 'Request appointment' }))
expect(await screen.findByText('Enter your full name')).toBeOnTheScreen()
expect(screen.getByText('Enter your mobile number')).toBeOnTheScreen()
expect(screen.getByText('Enter your date of birth')).toBeOnTheScreen()
expect(screen.getByText('Tell us in a few words why you are coming')).toBeOnTheScreen()
expect(announce).toHaveBeenCalledWith(
'Check 4 fields: Full name, Mobile number, Date of birth, Reason for the visit',
)
expect(onSubmit).not.toHaveBeenCalled()
})
test('sends a trimmed request with the phone in E.164 form', async () => {
const onSubmit = jest.fn(async () => {})
const user = userEvent.setup()
await render(<BookingForm onSubmit={onSubmit} />)
await fillValidForm(user)
await user.press(screen.getByRole('button', { name: 'Request appointment' }))
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith({
fullName: 'Amina Yusuf',
phone: '+2348031234567',
dateOfBirth: '1990-04-23',
reason: 'Blood pressure check',
}),
)
})
test('ignores a second tap while the first request is sending', async () => {
let finish: () => void = () => {}
const onSubmit = jest.fn(() => new Promise<void>((resolve) => (finish = resolve)))
const user = userEvent.setup()
await render(<BookingForm onSubmit={onSubmit} />)
await fillValidForm(user)
await user.press(screen.getByRole('button', { name: 'Request appointment' }))
const sendingButton = await screen.findByRole('button', { name: 'Sending' })
expect(sendingButton).toBeDisabled()
await user.press(sendingButton)
finish()
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Request appointment' })).toBeEnabled(),
)
// Counted only after the form has settled: a second submit runs the async
// Zod check before it would call onSubmit, so an earlier count could miss it.
expect(onSubmit).toHaveBeenCalledTimes(1)
})
TSX
npx jest src/componentsThe spy on announceForAccessibility replaces the real call, so the test checks the exact words a screen reader user hears.
Check it worked
Jest reports Tests: 3 passed, 3 total. Run the whole suite, which includes the schema tests and part 1's smoke test:
npx jestTo see the guards earn their place, take both out, run the tests, and put the originals back. The command below changes disabled={isSubmitting} to disabled={false} and deletes the if (sending.current) return line. It also drops the test's toBeDisabled() line, which would otherwise fail first and hide what happens next. Then it expects Jest to fail with two calls to onSubmit, restores both files and runs the tests again:
cp src/components/BookingForm.tsx /tmp/BookingForm.original.tsx
cp src/components/BookingForm.test.tsx /tmp/BookingForm.original.test.tsx
node -e "
const fs = require('fs')
const edit = (file, from, to) => {
const src = fs.readFileSync(file, 'utf8')
if (src.indexOf(from) === -1) throw new Error('Not found in ' + file + ': ' + from)
fs.writeFileSync(file, src.replace(from, to))
}
edit('src/components/BookingForm.tsx', 'disabled={isSubmitting}', 'disabled={false}')
edit('src/components/BookingForm.tsx', ' if (sending.current) return\\n', '')
edit('src/components/BookingForm.test.tsx', ' expect(sendingButton).toBeDisabled()\\n', '')
"
if npx jest src/components > /tmp/without-guards.log 2>&1; then echo "the tests passed without the guards"; false; fi
grep "Received number of calls: 2" /tmp/without-guards.log
cp /tmp/BookingForm.original.tsx src/components/BookingForm.tsx
cp /tmp/BookingForm.original.test.tsx src/components/BookingForm.test.tsx
rm /tmp/BookingForm.original.tsx /tmp/BookingForm.original.test.tsx /tmp/without-guards.log
npx jest src/componentsWithout the guards Jest fails on the third test and grep prints Received number of calls: 2: the second tap sent a second request. After the restore, the last run reports Tests: 3 passed, 3 total again.
Next steps
- Revisit the design decisions behind this screen: design form errors and inline validation.
- Grow the tests into a full suite later in the series: test the Larkfield app with Jest and React Native Testing Library.
Part of these paths
Related tutorials
- Test the Larkfield app with Jest and React Native Testing LibraryYou will have one Jest suite for the Larkfield Expo app that fakes only the native modules and the network, tests screens by role and label, opens routes by URL, controls the clock and retry timer, enforces coverage floors for the data and sync code and runs on every pull request.
- Get the Larkfield app ready for release: accessibility, versions and a Maestro smoke testYou will take the Larkfield Clinic Expo app through a release checklist, with tested accessible slot buttons, a version policy EAS enforces, the icon, splash and permissions checked by one script, and a Maestro flow that books an appointment, then hand it to EAS and clean up the series.
- Write end-to-end mobile tests with MaestroYou will have a small Maestro suite for a mobile app, with stable test IDs in React Native or Flutter, a shared sign-in flow fed by environment variables, smoke and full runs split by tags, and a CI job that runs the smoke flows on an Android emulator.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials