Skip to main content

Mobile development · Intermediate · 24 min

Make a React Native app work with TalkBack and VoiceOver

By Padding · Updated 18 Nov 2026
Expo SDK 58 · React Native 0.88.1 · React Native Testing Library 14.1.0 · Node.js 26 (node:26)

You will fix six screen reader problems in an Expo time-slot picker, guard each fix with a React Native Testing Library test that finds elements by role and name, and have a gesture-by-gesture script for checking it with TalkBack and VoiceOver.

On this page

A screen reader turns your app into a list. TalkBack on Android and VoiceOver on iOS move through the screen one element at a time, speak each element's name, its role ("button", "heading") and its state ("selected", "dimmed"), and let the person double-tap to act. Everything a sighted person reads from layout, colour and motion has to be in that list too, or it does not exist for them.

React Native passes your accessibility props straight to those native screen readers, so most fixes are a few props in the right places. The hard part is knowing which places. In this tutorial you build a small clinic time-slot picker with six realistic problems, fix them one by one, and write a React Native Testing Library (RNTL) test for each. The tests find elements the way a screen reader user does, by role and name, so if someone later removes a label or a state, the test run fails before the change ships.

This matters well beyond a small group of users. In many African markets the phone in someone's hand is a low-cost Android, and TalkBack on that phone is how a blind or low-vision customer hears your app. Large text and reduced motion, also covered here, are used by far more people than screen readers are.

Step 1 · Build the time-slot picker with its six problems

Create a throwaway app. When it asks to download create-expo-app, answer y:

Bash
cd ~
npx create-expo-app@5.0.0 screen-reader-slots-demo

The picker lives in its own folder, split into small files so each fix later replaces one whole file. Start with the data: three days and four slots, one of them full.

Bash
cd ~/screen-reader-slots-demo
mkdir -p src/slots
cat > src/slots/data.ts <<'TS'
export type Day = { id: string; weekday: string; dayOfMonth: number; month: string }
export type Slot = { id: string; time: string; clinician: string; full: boolean }
export type Booking = { id: string; day: string; time: string; clinician: string }

export const DAYS: Day[] = [
  { id: '2026-11-17', weekday: 'Tuesday', dayOfMonth: 17, month: 'November' },
  { id: '2026-11-18', weekday: 'Wednesday', dayOfMonth: 18, month: 'November' },
  { id: '2026-11-19', weekday: 'Thursday', dayOfMonth: 19, month: 'November' },
]

export const SLOTS: Slot[] = [
  { id: '0900', time: '09:00', clinician: 'Dr Okafor', full: false },
  { id: '0930', time: '09:30', clinician: 'Dr Okafor', full: true },
  { id: '1000', time: '10:00', clinician: 'Nurse Mensah', full: false },
  { id: '1030', time: '10:30', clinician: 'Dr Okafor', full: false },
]

export function dayLabel(day: Day): string {
  return `${day.weekday} ${day.dayOfMonth} ${day.month}`
}
TS

Now the four pieces of interface, written the way they often are when nobody has listened to them: a day header with arrow buttons, a slot button with a pulse when selected, a booking row you swipe left to cancel, and fixed-size styles.

Bash
cd ~/screen-reader-slots-demo
cat > src/slots/day-header.tsx <<'TSX'
import { Pressable, StyleSheet, Text, View } from 'react-native'
import type { Day } from './data'

type Props = {
  day: Day
  canGoBack: boolean
  canGoForward: boolean
  onPrevious: () => void
  onNext: () => void
}

export function DayHeader({ day, canGoBack, canGoForward, onPrevious, onNext }: Props) {
  return (
    <View style={styles.row}>
      <Pressable onPress={canGoBack ? onPrevious : undefined} style={[styles.arrow, !canGoBack && styles.dim]}>
        <Text style={styles.arrowText}>‹</Text>
      </Pressable>
      <View style={styles.date}>
        <Text style={styles.small}>{day.weekday.slice(0, 3)}</Text>
        <Text style={styles.big}>{day.dayOfMonth}</Text>
        <Text style={styles.small}>{day.month.slice(0, 3)}</Text>
      </View>
      <Pressable onPress={canGoForward ? onNext : undefined} style={[styles.arrow, !canGoForward && styles.dim]}>
        <Text style={styles.arrowText}>›</Text>
      </Pressable>
    </View>
  )
}

const styles = StyleSheet.create({
  row: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16 },
  arrow: { minWidth: 48, minHeight: 48, alignItems: 'center', justifyContent: 'center' },
  arrowText: { fontSize: 28 },
  dim: { opacity: 0.3 },
  date: { alignItems: 'center' },
  small: { fontSize: 14 },
  big: { fontSize: 28, fontWeight: '600' },
})
TSX
cat > src/slots/slot-styles.ts <<'TS'
import { StyleSheet } from 'react-native'

export const slotStyles = StyleSheet.create({
  grid: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, paddingHorizontal: 16 },
  slot: {
    width: 96,
    height: 44,
    overflow: 'hidden',
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: '#6a707b',
    borderRadius: 8,
  },
  selected: { borderWidth: 3, borderColor: '#0b0c0e', backgroundColor: '#d9dce1' },
  full: { opacity: 0.4 },
  time: { fontSize: 16, fontWeight: '600' },
  detail: { fontSize: 12 },
})
TS
cat > src/slots/use-pulse.ts <<'TS'
import { useEffect, useRef } from 'react'
import { Animated } from 'react-native'

// Gently scales the selected slot up and down, forever.
export function usePulse(active: boolean): Animated.Value {
  const scale = useRef(new Animated.Value(1)).current

  useEffect(() => {
    if (!active) return
    const loop = Animated.loop(
      Animated.sequence([
        Animated.timing(scale, { toValue: 1.06, duration: 400, useNativeDriver: true }),
        Animated.timing(scale, { toValue: 1, duration: 400, useNativeDriver: true }),
      ]),
    )
    loop.start()
    return () => {
      loop.stop()
      scale.setValue(1)
    }
  }, [active, scale])

  return scale
}
TS
cat > src/slots/slot-button.tsx <<'TSX'
import { Animated, Pressable, Text } from 'react-native'
import type { Slot } from './data'
import { slotStyles as styles } from './slot-styles'
import { usePulse } from './use-pulse'

type Props = { slot: Slot; selected: boolean; onSelect: (id: string) => void }

export function SlotButton({ slot, selected, onSelect }: Props) {
  const scale = usePulse(selected)

  return (
    <Pressable
      onPress={() => onSelect(slot.id)}
      style={[styles.slot, selected && styles.selected, slot.full && styles.full]}
    >
      <Animated.View style={{ transform: [{ scale }] }}>
        <Text style={styles.time}>{slot.time}</Text>
        <Text style={styles.detail}>{slot.full ? 'Full' : slot.clinician}</Text>
      </Animated.View>
    </Pressable>
  )
}
TSX
cat > src/slots/booking-row.tsx <<'TSX'
import { useRef } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import type { Booking } from './data'

type Props = { booking: Booking; onCancel: (id: string) => void }

const SWIPE_DISTANCE = 80

export function BookingRow({ booking, onCancel }: Props) {
  const startX = useRef(0)

  return (
    <View
      onTouchStart={(event) => {
        startX.current = event.nativeEvent.pageX
      }}
      onTouchEnd={(event) => {
        if (startX.current - event.nativeEvent.pageX > SWIPE_DISTANCE) onCancel(booking.id)
      }}
      style={styles.row}
    >
      <Text style={styles.time}>
        {booking.time} · {booking.clinician}
      </Text>
      <Text>{booking.day}</Text>
      <Text style={styles.tip}>Swipe left to cancel</Text>
    </View>
  )
}

const styles = StyleSheet.create({
  row: { padding: 16, borderBottomWidth: 1, borderColor: '#d9dce1' },
  time: { fontSize: 16, fontWeight: '600' },
  tip: { fontSize: 12, color: '#6a707b' },
})
TSX

Last, the screen that puts them together, and a route so you can open it:

Bash
cd ~/screen-reader-slots-demo
cat > src/slots/slot-picker.tsx <<'TSX'
import { useState } from 'react'
import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'
import { BookingRow } from './booking-row'
import { DAYS, SLOTS, dayLabel, type Booking } from './data'
import { DayHeader } from './day-header'
import { SlotButton } from './slot-button'
import { slotStyles } from './slot-styles'

export function SlotPicker() {
  const [dayIndex, setDayIndex] = useState(1)
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [bookings, setBookings] = useState<Booking[]>([])
  const [lastBooked, setLastBooked] = useState<Booking | null>(null)

  const day = DAYS[dayIndex]
  const selected = SLOTS.find((slot) => slot.id === selectedId)

  function changeDay(step: number) {
    setDayIndex((index) => Math.min(DAYS.length - 1, Math.max(0, index + step)))
    setSelectedId(null)
  }

  function select(id: string) {
    const slot = SLOTS.find((s) => s.id === id)
    if (slot && !slot.full) setSelectedId(id)
  }

  function book() {
    if (!selected) return
    const booking: Booking = {
      id: `${day.id}-${selected.id}`,
      day: dayLabel(day),
      time: selected.time,
      clinician: selected.clinician,
    }
    setBookings((all) => (all.some((b) => b.id === booking.id) ? all : [...all, booking]))
    setLastBooked(booking)
    setSelectedId(null)
  }

  function cancel(id: string) {
    setBookings((all) => all.filter((b) => b.id !== id))
    setLastBooked((current) => (current?.id === id ? null : current))
  }

  return (
    <ScrollView contentContainerStyle={styles.page}>
      <DayHeader
        day={day}
        canGoBack={dayIndex > 0}
        canGoForward={dayIndex < DAYS.length - 1}
        onPrevious={() => changeDay(-1)}
        onNext={() => changeDay(1)}
      />
      <View style={slotStyles.grid}>
        {SLOTS.map((slot) => (
          <SlotButton key={slot.id} slot={slot} selected={slot.id === selectedId} onSelect={select} />
        ))}
      </View>
      {selected ? (
        <Pressable accessibilityRole="button" onPress={book} style={styles.book}>
          <Text style={styles.bookText}>Book this time</Text>
        </Pressable>
      ) : null}
      {lastBooked ? (
        <View style={styles.confirmation}>
          <Text style={styles.heading}>{`Booked for ${lastBooked.time}`}</Text>
          <Text>{`${lastBooked.day} with ${lastBooked.clinician}`}</Text>
        </View>
      ) : null}
      <Text style={styles.heading}>Your bookings</Text>
      {bookings.map((booking) => (
        <BookingRow key={booking.id} booking={booking} onCancel={cancel} />
      ))}
    </ScrollView>
  )
}

const styles = StyleSheet.create({
  page: { paddingBottom: 48, gap: 16 },
  book: { marginHorizontal: 16, minHeight: 48, justifyContent: 'center', alignItems: 'center', backgroundColor: '#0b0c0e', borderRadius: 8 },
  bookText: { color: '#ffffff', fontSize: 16, fontWeight: '600' },
  confirmation: { marginHorizontal: 16, padding: 16, backgroundColor: '#f1f2f4', borderRadius: 8 },
  heading: { fontSize: 20, fontWeight: '600', paddingHorizontal: 16 },
})
TSX
cat > src/app/slots.tsx <<'TSX'
import { SlotPicker } from '@/slots/slot-picker'

export default function SlotsScreen() {
  return <SlotPicker />
}
TSX

Check it worked

Bash
cd ~/screen-reader-slots-demo
ls src/slots

The listing shows seven files, from booking-row.tsx to use-pulse.ts. If you have a phone, run npx expo start, open the app in Expo Go, go to the /slots route and turn on TalkBack or VoiceOver. Swipe through the screen and note what you hear: the arrows have no useful name, the date takes three swipes, no slot says it is a button or which one is selected, the full slot sounds the same as the others, and there is no way to cancel a booking.

Bash
npx expo start

Step 2 · Write tests that look for things the way a screen reader does

Each test below states one thing a screen reader user needs. They all use getByRole with a name, which matches an element only if it is exposed to assistive technology with that role, and its accessible name: the accessibilityLabel if there is one, otherwise the text inside it. That is close to what TalkBack and VoiceOver announce.

Install Jest with the Expo preset and RNTL 14:

Bash
cd ~/screen-reader-slots-demo
npx expo install --dev jest-expo jest @types/jest
npm install --save-dev @testing-library/react-native@14.1.0 test-renderer@1.3.1
npm pkg set jest.preset=jest-expo scripts.test=jest

Now the tests. React Native's Jest preset already replaces AccessibilityInfo with mock functions, so a test can check that the app asked the screen reader to move focus without a phone.

Bash
cd ~/screen-reader-slots-demo
cat > src/slots/slot-picker.test.tsx <<'TSX'
import { AccessibilityInfo } from 'react-native'
import { render, screen, userEvent } from '@testing-library/react-native'
import { SlotPicker } from './slot-picker'

beforeEach(() => {
  jest.clearAllMocks()
})

async function bookTenOClock() {
  const user = userEvent.setup()
  await render(<SlotPicker />)
  await user.press(screen.getByRole('button', { name: /^10:00/ }))
  await user.press(screen.getByRole('button', { name: 'Book this time' }))
  return user
}

describe('day header', () => {
  test('the arrow buttons have names and a disabled state', async () => {
    const user = userEvent.setup()
    await render(<SlotPicker />)

    await user.press(screen.getByRole('button', { name: 'Previous day' }))

    expect(screen.getByRole('button', { name: 'Previous day' })).toBeDisabled()
    expect(screen.getByRole('button', { name: 'Next day' })).toBeEnabled()
  })

  test('the date is read as one heading', async () => {
    await render(<SlotPicker />)

    expect(screen.getByRole('header', { name: 'Wednesday 18 November' })).toBeOnTheScreen()
  })
})

describe('slots', () => {
  test('each slot is a button that says if it is selected or full', async () => {
    const user = userEvent.setup()
    await render(<SlotPicker />)

    expect(screen.getByRole('button', { name: /^09:30/, disabled: true })).toBeOnTheScreen()

    await user.press(screen.getByRole('button', { name: /^10:00/ }))

    expect(screen.getByRole('button', { name: /^10:00/ })).toBeSelected()
    expect(screen.getByRole('button', { name: /^09:00/ })).not.toBeSelected()
  })
})

describe('cancelling', () => {
  test('a booking can be cancelled without swiping', async () => {
    const user = await bookTenOClock()

    const row = screen.getByLabelText('10:00 with Nurse Mensah, Wednesday 18 November')
    await user.accessibilityAction(row, 'cancel')

    expect(screen.queryByLabelText(/with Nurse Mensah/)).toBeNull()
  })
})

describe('focus', () => {
  test('moves to the confirmation heading after booking', async () => {
    await bookTenOClock()

    expect(screen.getByRole('header', { name: 'Booked for 10:00' })).toBeOnTheScreen()
    expect(AccessibilityInfo.sendAccessibilityEvent).toHaveBeenCalledWith(expect.anything(), 'focus')
  })
})

describe('large text', () => {
  test('a slot grows with its text instead of clipping it', async () => {
    await render(<SlotPicker />)
    const slot = screen.getByRole('button', { name: /^09:00/ })

    expect(slot).not.toHaveStyle({ height: 44 })
    expect(slot).toHaveStyle({ minHeight: 48 })
  })
})
TSX

The slot names use a regular expression, /^10:00/, because a slot's name is its time followed by the clinician or "Full". Anchoring at the start keeps 10:00 from matching anything else that mentions the time.

Run the file. Every test should fail, because the picker has every problem:

Bash
npx jest src/slots

Check it worked

Jest reports Tests: 6 failed, 6 total. Read the first failure: it says it is unable to find an element with role "button" and name "Previous day". That message is close to what a TalkBack user experiences.

Step 3 · Name the arrow buttons and read the date as one heading

Two problems live in the day header.

The arrows are icon-only buttons. A screen reader either says nothing useful or reads the glyph itself, something like "single left-pointing angle quotation mark". Give each a role and an accessibilityLabel. A label replaces the visible text for the screen reader, so use one only when the visible text is missing or meaningless, as here. When a control does have visible words, keep them at the start of its label, because people using Voice Access or Voice Control say what they see (WCAG calls this "label in name").

The date is three Text elements, so it takes three swipes: "Wed", "18", "Nov". Wrap them in a View with accessible set: that groups the children into one element. Give the group the full date as its label, so the abbreviations are expanded, and the header role, so it works as a heading people can jump to.

The arrows also need a real disabled state. Dimming with opacity tells nobody using a screen reader that the button does nothing.

Bash
cd ~/screen-reader-slots-demo
cat > src/slots/day-header.tsx <<'TSX'
import { Pressable, StyleSheet, Text, View } from 'react-native'
import { dayLabel, type Day } from './data'

type Props = {
  day: Day
  canGoBack: boolean
  canGoForward: boolean
  onPrevious: () => void
  onNext: () => void
}

export function DayHeader({ day, canGoBack, canGoForward, onPrevious, onNext }: Props) {
  return (
    <View style={styles.row}>
      <Pressable
        accessibilityRole="button"
        accessibilityLabel="Previous day"
        disabled={!canGoBack}
        onPress={onPrevious}
        style={[styles.arrow, !canGoBack && styles.dim]}
      >
        <Text style={styles.arrowText}>‹</Text>
      </Pressable>
      {/* One element for the screen reader: "Wednesday 18 November, heading" */}
      <View accessible accessibilityRole="header" accessibilityLabel={dayLabel(day)} style={styles.date}>
        <Text style={styles.small}>{day.weekday.slice(0, 3)}</Text>
        <Text style={styles.big}>{day.dayOfMonth}</Text>
        <Text style={styles.small}>{day.month.slice(0, 3)}</Text>
      </View>
      <Pressable
        accessibilityRole="button"
        accessibilityLabel="Next day"
        disabled={!canGoForward}
        onPress={onNext}
        style={[styles.arrow, !canGoForward && styles.dim]}
      >
        <Text style={styles.arrowText}>›</Text>
      </Pressable>
    </View>
  )
}

const styles = StyleSheet.create({
  row: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding: 16 },
  arrow: { minWidth: 48, minHeight: 48, alignItems: 'center', justifyContent: 'center' },
  arrowText: { fontSize: 28 },
  dim: { opacity: 0.3 },
  date: { alignItems: 'center' },
  small: { fontSize: 14 },
  big: { fontSize: 28, fontWeight: '600' },
})
TSX
npx jest src/slots -t "^day header" --ci

Pressable copies its disabled prop into accessibilityState, so TalkBack says "disabled" and VoiceOver "dimmed" without anything extra.

Check it worked

Jest reports 2 passed and 4 skipped. With a screen reader on, the date is now a single stop that says "Wednesday 18 November, heading", and the left arrow on the first day says "Previous day, button, disabled" (the exact wording differs between TalkBack and VoiceOver).

Step 4 · Give every slot a role and a state

A slot is a Pressable, and a Pressable already groups everything inside it into one element, so the time and the clinician are read together. What is missing is what the slot is and what condition it is in:

  • accessibilityRole="button" so it is announced as something you can activate.
  • accessibilityState.selected so the chosen slot says "selected". Right now only its border and fill show the choice.
  • disabled for a full slot. At the moment it can be focused and double-tapped, and nothing happens, with no explanation.

Leave out accessibilityLabel here. The visible text, "10:00 Nurse Mensah", is already a good name, and a hand-written label can drift out of step with what is on screen. Leave out accessibilityHint as well. A hint is read after a pause on every visit, and "double-tap to select" only repeats what the role already tells people. Save hints for actions whose result is not obvious from the name, as in the focus step below.

Bash
cd ~/screen-reader-slots-demo
cat > src/slots/slot-button.tsx <<'TSX'
import { Animated, Pressable, Text } from 'react-native'
import type { Slot } from './data'
import { slotStyles as styles } from './slot-styles'
import { usePulse } from './use-pulse'

type Props = { slot: Slot; selected: boolean; onSelect: (id: string) => void }

export function SlotButton({ slot, selected, onSelect }: Props) {
  const scale = usePulse(selected)

  return (
    <Pressable
      accessibilityRole="button"
      accessibilityState={{ selected, disabled: slot.full }}
      disabled={slot.full}
      onPress={() => onSelect(slot.id)}
      style={[styles.slot, selected && styles.selected, slot.full && styles.full]}
    >
      {/* No label: the visible time and clinician are the name. */}
      <Animated.View style={{ transform: [{ scale }] }}>
        <Text style={styles.time}>{slot.time}</Text>
        <Text style={styles.detail}>{slot.full ? 'Full' : slot.clinician}</Text>
      </Animated.View>
    </Pressable>
  )
}
TSX
npx jest src/slots -t "^slots" --ci

Check it worked

Jest reports 1 passed and 5 skipped. The test proves the 09:30 slot is exposed as disabled, and that pressing 10:00 makes it the only selected slot. On a phone, the full slot is read as something like "09:30, Full, button, disabled", and 10:00 adds "selected" once you double-tap it.

Step 5 · Give swipe-to-cancel a screen reader action

With TalkBack or VoiceOver on, a one-finger swipe moves focus to the next element; it never reaches your onTouchStart handler. So a swipe-to-delete row cannot be used at all by screen reader users. Custom accessibility actions fix that: you declare named actions on the element, and the screen reader offers them in its actions menu (TalkBack) or the Actions rotor (VoiceOver). onAccessibilityAction receives the name of the one the person picked.

The row also needs to be one element with a sensible name, instead of three separate lines ending with an instruction to swipe that does not apply to the person hearing it.

Bash
cd ~/screen-reader-slots-demo
cat > src/slots/booking-row.tsx <<'TSX'
import { useRef } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import type { Booking } from './data'

type Props = { booking: Booking; onCancel: (id: string) => void }

const SWIPE_DISTANCE = 80

export function BookingRow({ booking, onCancel }: Props) {
  const startX = useRef(0)

  return (
    <View
      accessible
      accessibilityLabel={`${booking.time} with ${booking.clinician}, ${booking.day}`}
      accessibilityActions={[{ name: 'cancel', label: 'Cancel booking' }]}
      onAccessibilityAction={(event) => {
        if (event.nativeEvent.actionName === 'cancel') onCancel(booking.id)
      }}
      onTouchStart={(event) => {
        startX.current = event.nativeEvent.pageX
      }}
      onTouchEnd={(event) => {
        if (startX.current - event.nativeEvent.pageX > SWIPE_DISTANCE) onCancel(booking.id)
      }}
      style={styles.row}
    >
      <Text style={styles.time}>
        {booking.time} · {booking.clinician}
      </Text>
      <Text>{booking.day}</Text>
      <Text style={styles.tip}>Swipe left to cancel</Text>
    </View>
  )
}

const styles = StyleSheet.create({
  row: { padding: 16, borderBottomWidth: 1, borderColor: '#d9dce1' },
  time: { fontSize: 16, fontWeight: '600' },
  tip: { fontSize: 12, color: '#6a707b' },
})
TSX
npx jest src/slots -t "^cancelling" --ci

The action helps screen reader users only. People with a tremor, or anyone using one thumb on a bus, may not manage a swipe either, and WCAG's Pointer Gestures criterion asks for a single-tap way to do the same thing. In a real app, add a visible Cancel button on the booking's detail screen as well.

Check it worked

Jest reports 1 passed and 5 skipped. userEvent.accessibilityAction throws if the element does not declare the action, so this test fails if anyone removes accessibilityActions, not only if the handler breaks.

Step 6 · Move focus to the confirmation after booking

When you book, the Book button disappears and a confirmation appears further down. The screen reader's focus was on the button that no longer exists, so it jumps somewhere else, often back to the top, and the person never hears that the booking worked.

Move focus yourself. Put a ref on the confirmation heading, and once it has rendered, call AccessibilityInfo.sendAccessibilityEvent(ref, 'focus'). Older guides use AccessibilityInfo.setAccessibilityFocus(findNodeHandle(ref)); in React Native 0.88 that is marked deprecated in favour of sendAccessibilityEvent. The same pattern applies after navigating to a new screen: focus the new screen's heading.

This version of the picker also gives "Your bookings" the heading role, announces a cancellation (the row that had focus has gone, so say what happened), and adds the one hint in the app, on the Book button, where the result is not obvious from its name.

Bash
cd ~/screen-reader-slots-demo
cat > src/slots/slot-picker.tsx <<'TSX'
import { useEffect, useRef, useState, type ComponentRef } from 'react'
import { AccessibilityInfo, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'
import { BookingRow } from './booking-row'
import { DAYS, SLOTS, dayLabel, type Booking } from './data'
import { DayHeader } from './day-header'
import { SlotButton } from './slot-button'
import { slotStyles } from './slot-styles'

export function SlotPicker() {
  const [dayIndex, setDayIndex] = useState(1)
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [bookings, setBookings] = useState<Booking[]>([])
  const [lastBooked, setLastBooked] = useState<Booking | null>(null)
  const confirmationRef = useRef<ComponentRef<typeof Text>>(null)

  const day = DAYS[dayIndex]
  const selected = SLOTS.find((slot) => slot.id === selectedId)

  // After a booking, the Book button is gone: put the screen reader on the confirmation.
  useEffect(() => {
    if (lastBooked && confirmationRef.current) {
      AccessibilityInfo.sendAccessibilityEvent(confirmationRef.current, 'focus')
    }
  }, [lastBooked])

  function changeDay(step: number) {
    setDayIndex((index) => Math.min(DAYS.length - 1, Math.max(0, index + step)))
    setSelectedId(null)
  }

  function select(id: string) {
    const slot = SLOTS.find((s) => s.id === id)
    if (slot && !slot.full) setSelectedId(id)
  }

  function book() {
    if (!selected) return
    const booking: Booking = {
      id: `${day.id}-${selected.id}`,
      day: dayLabel(day),
      time: selected.time,
      clinician: selected.clinician,
    }
    setBookings((all) => (all.some((b) => b.id === booking.id) ? all : [...all, booking]))
    setLastBooked(booking)
    setSelectedId(null)
  }

  function cancel(id: string) {
    const booking = bookings.find((b) => b.id === id)
    setBookings((all) => all.filter((b) => b.id !== id))
    setLastBooked((current) => (current?.id === id ? null : current))
    // The focused row has gone, so say what happened.
    if (booking) AccessibilityInfo.announceForAccessibility(`Booking for ${booking.time} cancelled`)
  }

  return (
    <ScrollView contentContainerStyle={styles.page}>
      <DayHeader
        day={day}
        canGoBack={dayIndex > 0}
        canGoForward={dayIndex < DAYS.length - 1}
        onPrevious={() => changeDay(-1)}
        onNext={() => changeDay(1)}
      />
      <View style={slotStyles.grid}>
        {SLOTS.map((slot) => (
          <SlotButton key={slot.id} slot={slot} selected={slot.id === selectedId} onSelect={select} />
        ))}
      </View>
      {selected ? (
        <Pressable
          accessibilityRole="button"
          accessibilityHint="Holds this time for you. You can cancel it under Your bookings."
          onPress={book}
          style={styles.book}
        >
          <Text style={styles.bookText}>Book this time</Text>
        </Pressable>
      ) : null}
      {lastBooked ? (
        <View style={styles.confirmation}>
          <Text ref={confirmationRef} accessibilityRole="header" style={styles.heading}>
            {`Booked for ${lastBooked.time}`}
          </Text>
          <Text>{`${lastBooked.day} with ${lastBooked.clinician}`}</Text>
        </View>
      ) : null}
      <Text accessibilityRole="header" style={styles.heading}>
        Your bookings
      </Text>
      {bookings.map((booking) => (
        <BookingRow key={booking.id} booking={booking} onCancel={cancel} />
      ))}
    </ScrollView>
  )
}

const styles = StyleSheet.create({
  page: { paddingBottom: 48, gap: 16 },
  book: { marginHorizontal: 16, minHeight: 48, justifyContent: 'center', alignItems: 'center', backgroundColor: '#0b0c0e', borderRadius: 8 },
  bookText: { color: '#ffffff', fontSize: 16, fontWeight: '600' },
  confirmation: { marginHorizontal: 16, padding: 16, backgroundColor: '#f1f2f4', borderRadius: 8 },
  heading: { fontSize: 20, fontWeight: '600', paddingHorizontal: 16 },
})
TSX
npx jest src/slots -t "^(focus|cancelling)" --ci

Prefer moving focus over an announcement when there is something on screen to land on: the person can swipe on from the confirmation, or hear it again, while an announcement is spoken once and gone.

Check it worked

Jest reports 2 passed and 4 skipped: the new focus test, and the cancelling test again, since this file replaced the screen it runs on. On a phone, double-tapping Book this time should be followed straight away by "Booked for 10:00, heading".

Step 7 · Respect Reduce motion and large text

Two settings remain. The selected slot pulses forever, which some people with vestibular disorders find makes them dizzy, and phones let people turn motion down: Remove animations on Android, Reduce Motion on iOS. React Native reads both through AccessibilityInfo.isReduceMotionEnabled() and tells you about changes with the reduceMotionChanged event. Put that in a hook:

Bash
cd ~/screen-reader-slots-demo
cat > src/slots/use-reduced-motion.ts <<'TS'
import { useEffect, useState } from 'react'
import { AccessibilityInfo } from 'react-native'

// True when the person has asked the phone for less motion. Follows changes live.
export function usePrefersReducedMotion(): boolean {
  const [reduced, setReduced] = useState(false)

  useEffect(() => {
    let mounted = true
    AccessibilityInfo.isReduceMotionEnabled().then((value) => {
      if (mounted) setReduced(value)
    })
    const subscription = AccessibilityInfo.addEventListener('reduceMotionChanged', setReduced)
    return () => {
      mounted = false
      subscription.remove()
    }
  }, [])

  return reduced
}
TS
cat > src/slots/use-pulse.ts <<'TS'
import { useEffect, useRef } from 'react'
import { Animated } from 'react-native'
import { usePrefersReducedMotion } from './use-reduced-motion'

// Pulses the selected slot, unless the phone is set to reduce motion.
// The border and fill still show the selection either way.
export function usePulse(active: boolean): Animated.Value {
  const scale = useRef(new Animated.Value(1)).current
  const reduceMotion = usePrefersReducedMotion()

  useEffect(() => {
    if (!active || reduceMotion) return
    const loop = Animated.loop(
      Animated.sequence([
        Animated.timing(scale, { toValue: 1.06, duration: 400, useNativeDriver: true }),
        Animated.timing(scale, { toValue: 1, duration: 400, useNativeDriver: true }),
      ]),
    )
    loop.start()
    return () => {
      loop.stop()
      scale.setValue(1)
    }
  }, [active, reduceMotion, scale])

  return scale
}
TS
cat > src/slots/use-reduced-motion.test.ts <<'TS'
import { AccessibilityInfo } from 'react-native'
import { act, renderHook, waitFor } from '@testing-library/react-native'
import { usePrefersReducedMotion } from './use-reduced-motion'

beforeEach(() => {
  jest.clearAllMocks()
})

test('reads the setting when it mounts', async () => {
  jest.mocked(AccessibilityInfo.isReduceMotionEnabled).mockResolvedValueOnce(true)

  const { result } = await renderHook(() => usePrefersReducedMotion())

  await waitFor(() => expect(result.current).toBe(true))
})

test('follows the setting when it changes', async () => {
  // Never resolves, so only the change event can set the value.
  jest.mocked(AccessibilityInfo.isReduceMotionEnabled).mockReturnValueOnce(new Promise(() => {}))
  const { result } = await renderHook(() => usePrefersReducedMotion())

  const call = jest
    .mocked(AccessibilityInfo.addEventListener)
    .mock.calls.find(([eventName]) => eventName === 'reduceMotionChanged')
  const onChange = call?.[1] as (enabled: boolean) => void
  await act(async () => {
    onChange(true)
  })

  expect(result.current).toBe(true)
})
TS

If your app animates with Reanimated, it has its own useReducedMotion hook and a reduceMotion option on each animation, which do the same job.

The second setting is text size. People set it in Android's Font size or iOS's Larger Text, and React Native scales every Text to match. The slot has a fixed height: 44, a fixed width and overflow: 'hidden', so at the largest sizes the clinician's name is cut off. Let the slot grow: a minimum height instead of a height, a flexible width with wrapping, and no hidden overflow. While you are here, replace the 40% opacity on full slots, which makes the text too faint to read, with a dashed border; the word "Full" already carries the meaning.

Bash
cd ~/screen-reader-slots-demo
cat > src/slots/slot-styles.ts <<'TS'
import { StyleSheet } from 'react-native'

export const slotStyles = StyleSheet.create({
  grid: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, paddingHorizontal: 16 },
  // No fixed height or width: the slot grows with the phone's text size.
  slot: {
    flexGrow: 1,
    flexBasis: 140,
    minHeight: 48,
    paddingVertical: 8,
    paddingHorizontal: 12,
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: '#6a707b',
    borderRadius: 8,
  },
  selected: { borderWidth: 3, borderColor: '#0b0c0e', backgroundColor: '#d9dce1' },
  full: { borderStyle: 'dashed', backgroundColor: '#f1f2f4' },
  time: { fontSize: 16, fontWeight: '600' },
  detail: { fontSize: 14 },
})
TS
npx jest src/slots -t "^large text" --ci
npx jest src/slots/use-reduced-motion --ci

Do not reach for allowFontScaling={false} to protect a layout: it removes the text size people chose. If one tiny label truly cannot grow, maxFontSizeMultiplier caps it at a level you pick. For bigger layout changes, useWindowDimensions().fontScale tells you the current scale, so you can switch a two-column grid to one column above, say, 1.5.

Check it worked

The first Jest run reports 1 passed and 5 skipped, the second Tests: 2 passed, 2 total. On a phone, set the largest text size and open the picker: every slot grows taller and shows its full time and clinician.

Step 8 · Run every test and build the bundle

Run the whole suite, then export the Android JavaScript bundle to confirm the app still builds with every change:

Bash
cd ~/screen-reader-slots-demo
npm test -- --ci
npx expo export --platform android
grep -a -c "Previous day" dist/_expo/static/js/android/*.hbc

Run npm test -- --ci in your continuous integration before every build, so a pull request that drops a role or a label cannot merge. To see it work, delete accessibilityRole="button" from slot-button.tsx and run npm test again: four tests fail, each naming the role and name it could not find. Put it back afterwards.

These tests catch missing roles, names, states, actions and focus calls. They cannot tell you whether the reading order makes sense or whether a label sounds right when spoken, so they do not replace listening.

Check it worked

Jest reports two test suites and Tests: 8 passed, 8 total. The export finishes with the Android bundle in dist, and the grep prints 1 or more, so the new label is in the code that ships.

Step 9 · Test it by hand with TalkBack and VoiceOver

Run npx expo start, open the /slots route in Expo Go, and turn the screen reader on before you open the app. On Android: Settings, Accessibility, TalkBack. On iPhone: Settings, Accessibility, VoiceOver. Learn how to turn it off again first, because the usual taps stop working.

The gestures you need:

  • Next or previous element: swipe right or left, on both.
  • Activate: double-tap, on both.
  • Actions for an element: in TalkBack, open the TalkBack menu (three-finger tap, or swipe down then right) and choose Actions; in VoiceOver, rotate two fingers on the screen until you hear Actions, swipe up or down to pick one, then double-tap.
  • Read from the top: in VoiceOver, two-finger swipe up; TalkBack has no default gesture for it, but you can assign one in TalkBack's settings.

Then work through this script and write down anything that sounds wrong:

  1. Swipe from the top. The date is one stop, read in full and as a heading.
  2. Swipe to the left arrow on the first day: it is named and disabled. Activate Next day; the date heading changes.
  3. Swipe through the slots. Each is read as its time, then its clinician or Full, then button. The full slot is disabled.
  4. Double-tap 10:00. It says selected, and Book this time appears next, with its hint after a pause.
  5. Double-tap Book this time. Focus lands on "Booked for 10:00" without you swiping.
  6. Swipe to the booking row. It is one stop, and you are told actions are available. Choose Cancel booking: the row goes and you hear "Booking for 10:00 cancelled".
  7. Turn on Remove animations (Android) or Reduce Motion (iOS), select a slot: it no longer pulses.
  8. Set the largest text size: nothing is cut off.

If your labels are in a language that differs from the phone's, as in an app with Swahili, Hausa or Yorùbá content on an English-language phone, accessibilityLanguage tells VoiceOver which voice to use (it is iOS only). TalkBack reads with the phone's text-to-speech engine, so listen with the engine and languages your users have. And do at least one pass on the cheapest Android phone you support, since that is how many of your users will hear the app.

Check it worked

You have been through all eight checks on at least one platform, with a note of anything that sounded wrong. Fix what you found, add a test for it in the same style, and repeat the script on the other platform when you can.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.