Skip to main content

Mobile development · Beginner · 25 min

Handle the keyboard, notches and safe areas in React Native

By Padding · Updated 18 Nov 2026
Expo SDK 58 · react-native-safe-area-context 5.11 · react-native-keyboard-controller 1.22 · Node.js 26 (node:26)

You will have an Expo SDK 58 chat screen and form that clear the status bar, notch and home indicator edge by edge, keep the message box above the keyboard, dismiss the keyboard on scroll and work in landscape, with Jest tests that fake each phone's insets.

On this page

Phones no longer give your app a neat rectangle. On iOS the screen runs under the status bar, the notch or Dynamic Island, and the home indicator. On Android the same is now true: since Expo SDK 54 every Android app runs edge-to-edge, so your content is drawn under the status bar and the navigation bar unless you move it out of the way. Then the keyboard arrives and covers the bottom third of the screen, often including the very text box the person is typing into.

The space you must keep clear on each side is called an inset. This tutorial builds a small two-screen app, a chat with a pharmacy and a delivery details form, and handles insets the way production apps do: each piece of the screen pads only the edge it touches, the message box rides on top of the keyboard, the keyboard goes away when the person scrolls, and the layout still works on its side. You use react-native-safe-area-context for the insets and react-native-keyboard-controller for the keyboard, and you test the layout in Jest by pretending to be different phones.

Step 1 · Create the app and install the two libraries

Create a TypeScript app from the blank template in a practice folder. The @sdk-58 suffix fixes the template to Expo SDK 58:

Bash
cd ~
npx create-expo-app@5.0.0 insets-demo --template blank-typescript@sdk-58

Install the inset library, the keyboard library and the two animation packages the keyboard library is built on. npx expo install picks the versions that Expo has tested with SDK 58:

Bash
cd ~/insets-demo
npx expo install react-native-safe-area-context react-native-keyboard-controller react-native-reanimated react-native-worklets

The keyboard library's newest release on npm is 1.24, but SDK 58 lists 1.22.7, and that is the version Expo Go contains. Staying on the SDK's version means the app runs in Expo Go and npx expo install --check stays quiet. Every API in this tutorial exists in both.

Check it worked

Bash
cd ~/insets-demo
npm ls react-native-safe-area-context react-native-keyboard-controller --depth=0

The output lists react-native-safe-area-context@5.11.1 (or a later 5.11 patch) and react-native-keyboard-controller@1.22.7.

Step 2 · Pad the header for the status bar and notch

The common first fix is to wrap the whole screen in one SafeAreaView. It stops content hiding under the system bars, but it also leaves a band of plain background above your header and below your message box, because the padding sits outside them. Coloured headers stop short of the top of the screen, and the bottom bar floats above an empty strip.

Two phone outlines side by side. On the left, one SafeAreaView around the whole screen leaves grey bands above the Messages header and below the message box. On the right, the header's colour runs up behind the notch, the message list only uses the left and right insets, and the composer extends down behind the home indicator.
Pad each edge in the component that touches it.

The better rule is to pad each edge in the component that touches it. The header owns the top edge, so its background runs up behind the status bar while its text starts below it. useSafeAreaInsets returns the four insets as numbers, so you can add them to your own padding. Create the header:

Bash
cd ~/insets-demo
mkdir -p src/components
cat > src/components/ScreenHeader.tsx <<'TSX'
import { Pressable, StyleSheet, Text, View } from 'react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'

type Props = {
  title: string
  action?: { label: string; onPress: () => void }
}

export function ScreenHeader({ title, action }: Props) {
  const insets = useSafeAreaInsets()

  return (
    <View
      testID="screen-header"
      style={[
        styles.header,
        {
          paddingTop: insets.top + 12,
          paddingLeft: insets.left + 16,
          paddingRight: insets.right + 16,
        },
      ]}
    >
      <Text accessibilityRole="header" style={styles.title}>
        {title}
      </Text>
      {action ? (
        <Pressable accessibilityRole="button" onPress={action.onPress} hitSlop={12}>
          <Text style={styles.action}>{action.label}</Text>
        </Pressable>
      ) : null}
    </View>
  )
}

const styles = StyleSheet.create({
  header: {
    backgroundColor: '#2a2d33',
    paddingBottom: 12,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  title: { color: '#ffffff', fontSize: 20, fontWeight: '700' },
  action: { color: '#d9dce1', fontSize: 16 },
})
TSX

The header pads the top, left and right. Left and right are zero in portrait, but in landscape the notch moves to one side, and a header that ignores them puts its title under the camera. It does not pad the bottom: that edge touches your own content, not the phone's hardware.

The hook reads the insets from a SafeAreaProvider near the top of the app, which you add in a later step. Next, set up Jest. The library ships a Jest version of itself, where a SafeAreaProvider takes whatever insets you give it in initialMetrics. The keyboard library ships one too. Install Jest with Expo's preset and React Native Testing Library, and load both stand-ins from a setup file:

Bash
cd ~/insets-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
cat > jest.setup.ts <<'TS'
// Both libraries ship Jest versions of themselves that need no native code.
jest.mock('react-native-safe-area-context', () =>
  require('react-native-safe-area-context/jest/mock').default,
)
jest.mock('react-native-keyboard-controller', () =>
  require('react-native-keyboard-controller/jest'),
)
TS
npm pkg set jest.preset=jest-expo 'jest.setupFiles[0]=<rootDir>/jest.setup.ts' scripts.test=jest

Now describe a few phones as data. The numbers are typical, not exact for any model: a recent iPhone reports a top inset of about 59 points and 34 for the home indicator, an Android phone with gesture navigation has a short bottom inset, and one with the older three-button bar has a taller one. Many low-cost Android phones still ship with three-button navigation, so that is the bottom inset a lot of your users see.

Bash
cd ~/insets-demo
mkdir -p src/testing
cat > src/testing/phones.tsx <<'TSX'
import type { ReactNode } from 'react'
import { SafeAreaProvider, type Metrics } from 'react-native-safe-area-context'

// Typical insets in points (iOS) or density-independent pixels (Android).
export const phones = {
  iphonePortrait: {
    frame: { x: 0, y: 0, width: 393, height: 852 },
    insets: { top: 59, bottom: 34, left: 0, right: 0 },
  },
  iphoneLandscape: {
    frame: { x: 0, y: 0, width: 852, height: 393 },
    insets: { top: 0, bottom: 21, left: 59, right: 59 },
  },
  androidThreeButton: {
    frame: { x: 0, y: 0, width: 360, height: 800 },
    insets: { top: 24, bottom: 48, left: 0, right: 0 },
  },
} satisfies Record<string, Metrics>

export function onPhone(metrics: Metrics) {
  return function Wrapper({ children }: { children: ReactNode }) {
    return <SafeAreaProvider initialMetrics={metrics}>{children}</SafeAreaProvider>
  }
}
TSX

Test the header on two phones:

Bash
cd ~/insets-demo
cat > src/components/ScreenHeader.test.tsx <<'TSX'
import { render, screen } from '@testing-library/react-native'
import { onPhone, phones } from '../testing/phones'
import { ScreenHeader } from './ScreenHeader'

test('starts the title below the status bar and notch', async () => {
  await render(<ScreenHeader title="Messages" />, { wrapper: onPhone(phones.iphonePortrait) })

  expect(screen.getByRole('header', { name: 'Messages' })).toBeOnTheScreen()
  expect(screen.getByTestId('screen-header')).toHaveStyle({ paddingTop: 71, paddingLeft: 16 })
})

test('moves the title away from the notch in landscape', async () => {
  await render(<ScreenHeader title="Messages" />, { wrapper: onPhone(phones.iphoneLandscape) })

  expect(screen.getByTestId('screen-header')).toHaveStyle({
    paddingTop: 12,
    paddingLeft: 75,
    paddingRight: 75,
  })
})
TSX
npx jest src/components/ScreenHeader --ci

Check it worked

Jest reports Tests: 2 passed, 2 total. In portrait the title starts 71 points down (59 for the status bar plus your 12), and in landscape the top padding drops to 12 while each side grows to 75. To see the test catch a real mistake, change insets.left + 16 to 16 and run it again: the landscape test fails. Put it back.

Step 3 · Keep the message box above the home indicator

The message box, or composer, owns the bottom edge. While the keyboard is closed it must clear the home indicator or the Android navigation bar. While the keyboard is open, that bar is hidden behind the keyboard, so keeping the inset would leave a gap of empty space between the box and the keys.

Two phones. With the keyboard closed, the message box sits 34 points above the bottom edge, the height of the home indicator inset. With the keyboard open, the box rests on top of the keyboard with a fixed 8-point gap.
Drop the bottom inset while the keyboard covers it.

useKeyboardState from the keyboard library tells you whether the keyboard is showing. Pass it a selector, a small function that picks one value, so the component only re-renders when that value changes. Create the composer:

Bash
cd ~/insets-demo
cat > src/components/Composer.tsx <<'TSX'
import { useState } from 'react'
import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'
import { useKeyboardState } from 'react-native-keyboard-controller'
import { useSafeAreaInsets } from 'react-native-safe-area-context'

type Props = { onSend: (text: string) => void }

export function Composer({ onSend }: Props) {
  const insets = useSafeAreaInsets()
  const keyboardOpen = useKeyboardState((state) => state.isVisible)
  const [text, setText] = useState('')
  const message = text.trim()

  function send() {
    if (!message) return
    onSend(message)
    setText('')
  }

  return (
    <View
      testID="composer"
      style={[
        styles.bar,
        {
          // The keyboard hides the home indicator, so only keep its inset while it is closed.
          paddingBottom: keyboardOpen ? 8 : Math.max(insets.bottom, 8),
          paddingLeft: insets.left + 12,
          paddingRight: insets.right + 12,
        },
      ]}
    >
      <TextInput
        accessibilityLabel="Message"
        placeholder="Write a message"
        value={text}
        onChangeText={setText}
        multiline
        style={styles.input}
      />
      <Pressable
        accessibilityRole="button"
        accessibilityLabel="Send"
        disabled={!message}
        onPress={send}
        style={styles.send}
      >
        <Text style={[styles.sendText, !message && styles.sendDisabled]}>Send</Text>
      </Pressable>
    </View>
  )
}

const styles = StyleSheet.create({
  bar: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    gap: 8,
    paddingTop: 8,
    backgroundColor: '#ffffff',
    borderTopWidth: StyleSheet.hairlineWidth,
    borderTopColor: '#d9dce1',
  },
  input: {
    flex: 1,
    minHeight: 40,
    maxHeight: 120,
    paddingHorizontal: 14,
    paddingVertical: 10,
    borderRadius: 20,
    backgroundColor: '#f1f2f4',
    fontSize: 16,
  },
  send: { minHeight: 44, justifyContent: 'center', paddingHorizontal: 8 },
  sendText: { fontSize: 16, fontWeight: '600', color: '#0b0c0e' },
  sendDisabled: { color: '#9ba1ac' },
})
TSX

Math.max(insets.bottom, 8) keeps a minimum gap on phones with no bottom inset at all, such as older iPhones with a home button. The Send button is 44 points tall, a comfortable target on small screens.

In tests, the keyboard library's stand-in reports the keyboard as closed. To test the open state, replace what useKeyboardState returns for one test:

Bash
cd ~/insets-demo
cat > src/components/Composer.test.tsx <<'TSX'
import { render, screen } from '@testing-library/react-native'
import { useKeyboardState } from 'react-native-keyboard-controller'
import { onPhone, phones } from '../testing/phones'
import { Composer } from './Composer'

function keyboardIs(isVisible: boolean) {
  jest
    .mocked(useKeyboardState)
    .mockImplementation(((select: (state: { isVisible: boolean }) => unknown) =>
      select({ isVisible })) as typeof useKeyboardState)
}

beforeEach(() => keyboardIs(false))

test('clears the home indicator while the keyboard is closed', async () => {
  await render(<Composer onSend={jest.fn()} />, { wrapper: onPhone(phones.iphonePortrait) })

  expect(screen.getByTestId('composer')).toHaveStyle({ paddingBottom: 34 })
})

test('clears the three-button navigation bar on Android', async () => {
  await render(<Composer onSend={jest.fn()} />, { wrapper: onPhone(phones.androidThreeButton) })

  expect(screen.getByTestId('composer')).toHaveStyle({ paddingBottom: 48 })
})

test('drops the bottom inset while the keyboard is open', async () => {
  keyboardIs(true)
  await render(<Composer onSend={jest.fn()} />, { wrapper: onPhone(phones.iphonePortrait) })

  expect(screen.getByTestId('composer')).toHaveStyle({ paddingBottom: 8 })
})

test('keeps clear of the notch in landscape', async () => {
  await render(<Composer onSend={jest.fn()} />, { wrapper: onPhone(phones.iphoneLandscape) })

  expect(screen.getByTestId('composer')).toHaveStyle({
    paddingBottom: 21,
    paddingLeft: 71,
    paddingRight: 71,
  })
})

test('cannot send an empty message', async () => {
  await render(<Composer onSend={jest.fn()} />, { wrapper: onPhone(phones.iphonePortrait) })

  expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled()
})
TSX
npx jest src/components/Composer --ci

Check it worked

Jest reports Tests: 5 passed, 5 total. The bottom padding is 34 on the iPhone, 48 on the three-button Android phone, 8 with the keyboard open and 21 in landscape.

Step 4 · Keep the chat input above the keyboard

The keyboard does not push your layout up by itself. On iOS it has always covered the app, and on Android, now that apps are edge-to-edge, the window no longer shrinks for it either. A KeyboardAvoidingView adds bottom padding equal to the part of the keyboard that overlaps it, so whatever sits at its bottom edge moves up.

React Native has a built-in KeyboardAvoidingView, and with behavior="padding" it does the job on both platforms. The keyboard library has a drop-in replacement with the same props that follows the keyboard frame by frame on both iOS and Android, so the composer moves with the keys instead of jumping after them. Use that one. Create the chat screen:

Bash
cd ~/insets-demo
cat > src/components/ChatScreen.tsx <<'TSX'
import { useState } from 'react'
import { FlatList, Platform, StyleSheet, Text, View } from 'react-native'
import { KeyboardAvoidingView } from 'react-native-keyboard-controller'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { Composer } from './Composer'
import { ScreenHeader } from './ScreenHeader'

type Message = { id: string; text: string; fromMe: boolean }

const FIRST_MESSAGES: Message[] = [
  { id: '1', text: 'Hello. How can the pharmacy help today?', fromMe: false },
]

type Props = { onOpenDetails: () => void }

export function ChatScreen({ onOpenDetails }: Props) {
  const insets = useSafeAreaInsets()
  const [messages, setMessages] = useState(FIRST_MESSAGES)

  function addMessage(text: string) {
    setMessages((list) => [...list, { id: String(list.length + 1), text, fromMe: true }])
  }

  return (
    <View style={styles.screen}>
      <ScreenHeader title="Messages" action={{ label: 'Your details', onPress: onOpenDetails }} />
      <KeyboardAvoidingView behavior="padding" style={styles.body}>
        <FlatList
          testID="message-list"
          data={messages}
          keyExtractor={(item) => item.id}
          renderItem={({ item }) => (
            <Text style={[styles.bubble, item.fromMe ? styles.mine : styles.theirs]}>
              {item.text}
            </Text>
          )}
          contentContainerStyle={{
            paddingTop: 12,
            paddingLeft: insets.left + 16,
            paddingRight: insets.right + 16,
          }}
          keyboardDismissMode={Platform.OS === 'ios' ? 'interactive' : 'on-drag'}
          keyboardShouldPersistTaps="handled"
        />
        <Composer onSend={addMessage} />
      </KeyboardAvoidingView>
    </View>
  )
}

const styles = StyleSheet.create({
  screen: { flex: 1, backgroundColor: '#f1f2f4' },
  body: { flex: 1 },
  bubble: {
    maxWidth: '80%',
    marginBottom: 8,
    paddingHorizontal: 14,
    paddingVertical: 10,
    borderRadius: 16,
    fontSize: 16,
    overflow: 'hidden',
  },
  theirs: { alignSelf: 'flex-start', backgroundColor: '#ffffff', color: '#0b0c0e' },
  mine: { alignSelf: 'flex-end', backgroundColor: '#2a2d33', color: '#ffffff' },
})
TSX

The header sits outside the KeyboardAvoidingView. Only the list and the composer need to move. The avoiding view works out the overlap from its position inside its parent, and here the parent fills the whole screen, so no extra offset is needed. Inside a navigator that draws its own header, pass that header's height as keyboardVerticalOffset. The list pads only its sides: its top edge touches the header and its bottom edge touches the composer, neither of which is hardware.

Test that a message goes in and comes out. The second message uses Yorùbá with tone marks, a reminder to test with the languages your users type, not only English:

Bash
cd ~/insets-demo
cat > src/components/ChatScreen.test.tsx <<'TSX'
import { render, screen, userEvent } from '@testing-library/react-native'
import { onPhone, phones } from '../testing/phones'
import { ChatScreen } from './ChatScreen'

test('sends a message and clears the box', async () => {
  const user = userEvent.setup()
  await render(<ChatScreen onOpenDetails={jest.fn()} />, {
    wrapper: onPhone(phones.androidThreeButton),
  })

  await user.type(screen.getByLabelText('Message'), '  Do you have ORS sachets?  ')
  await user.press(screen.getByRole('button', { name: 'Send' }))

  expect(screen.getByText('Do you have ORS sachets?')).toBeOnTheScreen()
  expect(screen.getByLabelText('Message')).toHaveDisplayValue('')
})

test('keeps tone marks intact', async () => {
  const user = userEvent.setup()
  await render(<ChatScreen onOpenDetails={jest.fn()} />, {
    wrapper: onPhone(phones.iphonePortrait),
  })

  await user.type(screen.getByLabelText('Message'), 'Ẹ kú àárọ̀')
  await user.press(screen.getByRole('button', { name: 'Send' }))

  expect(screen.getByText('Ẹ kú àárọ̀')).toBeOnTheScreen()
})
TSX
npx jest src/components/ChatScreen --ci

Check it worked

Jest reports Tests: 2 passed, 2 total. The message is trimmed before it is added, and the box is empty afterwards. Jest cannot show the keyboard moving: you check that on a phone in the last step.

Step 5 · Dismiss the keyboard when the person scrolls

Once the keyboard is up, people expect to push it away by scrolling back through the conversation. Two props on the list in ChatScreen.tsx already handle this:

  • keyboardDismissMode is interactive on iOS, where the keyboard follows the finger down and can be pulled back up. Android does not support interactive and treats it as none, so Android gets on-drag, which closes the keyboard as soon as a scroll starts.
  • keyboardShouldPersistTaps="handled" lets a tap on something inside the list that responds to touch, such as a link or a retry button in a message, work on the first tap. A tap on empty space in the list still closes the keyboard. With the default, never, the first tap on a button only closes the keyboard and the button never hears it.

Add a test that pins both choices, so a later refactor cannot quietly remove them:

Bash
cd ~/insets-demo
cat > src/components/ChatScreen.keyboard.test.tsx <<'TSX'
import { render, screen } from '@testing-library/react-native'
import { onPhone, phones } from '../testing/phones'
import { ChatScreen } from './ChatScreen'

test('lets the person drag the keyboard away and tap inside messages', async () => {
  await render(<ChatScreen onOpenDetails={jest.fn()} />, {
    wrapper: onPhone(phones.iphonePortrait),
  })

  const list = screen.getByTestId('message-list')
  expect(list).toHaveProp('keyboardDismissMode', 'interactive')
  expect(list).toHaveProp('keyboardShouldPersistTaps', 'handled')
})
TSX
npx jest src/components/ChatScreen.keyboard --ci

Jest runs as iOS by default under the Expo preset, which is why the test expects interactive.

Check it worked

Jest reports Tests: 1 passed, 1 total. Change keyboardShouldPersistTaps="handled" to "never" in ChatScreen.tsx and run the test again: it fails and names the prop. Change it back.

Step 6 · Build a long form that scrolls to the focused field

A chat has one text box at the bottom. A form has several down the page, and when the person taps the last one, the keyboard covers it. KeyboardAwareScrollView from the keyboard library is a ScrollView that scrolls the focused field into view when the keyboard opens and when focus moves to the next field. bottomOffset sets how much space to keep between the field and the top of the keyboard.

This screen also shows when SafeAreaView is the right tool. When a plain view needs padding on fixed edges, SafeAreaView with an edges list is the shortest way to say so. Here it pads the top and sides. The bottom is left out on purpose: the form scrolls under the home indicator, and the scroll content adds the bottom inset as padding so the last field can still scroll clear of it. Create the screen:

Bash
cd ~/insets-demo
cat > src/components/DetailsScreen.tsx <<'TSX'
import { Platform, Pressable, StyleSheet, Text, TextInput, View, type TextInputProps } from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-controller'
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context'

function Field({ label, ...input }: { label: string } & TextInputProps) {
  return (
    <View style={styles.field}>
      <Text style={styles.label}>{label}</Text>
      <TextInput accessibilityLabel={label} style={styles.input} {...input} />
    </View>
  )
}

type Props = { onBack: () => void }

export function DetailsScreen({ onBack }: Props) {
  const insets = useSafeAreaInsets()

  return (
    // Top and sides only: the scroll content handles the bottom edge itself.
    <SafeAreaView testID="details-screen" edges={['top', 'left', 'right']} style={styles.screen}>
      <View style={styles.titleRow}>
        <Pressable accessibilityRole="button" onPress={onBack} hitSlop={12}>
          <Text style={styles.back}>Back</Text>
        </Pressable>
        <Text accessibilityRole="header" style={styles.title}>
          Your details
        </Text>
      </View>
      <KeyboardAwareScrollView
        testID="details-form"
        bottomOffset={24}
        keyboardShouldPersistTaps="handled"
        keyboardDismissMode={Platform.OS === 'ios' ? 'interactive' : 'on-drag'}
        contentContainerStyle={{ padding: 16, paddingBottom: insets.bottom + 24 }}
      >
        <Field label="Full name" autoComplete="name" textContentType="name" />
        <Field label="Phone number" keyboardType="phone-pad" autoComplete="tel" textContentType="telephoneNumber" />
        <Field label="Delivery address" multiline autoComplete="street-address" textContentType="fullStreetAddress" />
        <Field label="Landmark or directions" multiline />
        <Field label="Notes for the pharmacist" multiline />
      </KeyboardAwareScrollView>
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  screen: { flex: 1, backgroundColor: '#ffffff' },
  titleRow: { flexDirection: 'row', alignItems: 'center', gap: 16, padding: 16 },
  back: { fontSize: 16, color: '#2a2d33' },
  title: { fontSize: 20, fontWeight: '700', color: '#0b0c0e' },
  field: { marginBottom: 20 },
  label: { fontSize: 14, fontWeight: '600', color: '#2a2d33', marginBottom: 6 },
  input: {
    minHeight: 48,
    paddingHorizontal: 12,
    paddingVertical: 12,
    borderWidth: 1,
    borderColor: '#9ba1ac',
    borderRadius: 8,
    fontSize: 16,
    color: '#0b0c0e',
  },
})
TSX

Do not put the ScreenHeader from earlier inside this SafeAreaView: both would add the top inset, and the title would sit twice as far down as it should. Pick one owner for each edge. The "Landmark or directions" field is there because in many cities, including much of urban Africa, a landmark gets a delivery rider to the door more reliably than a street address.

SafeAreaView pads itself on the native side, so in Jest you check which edges it was asked to pad, not the resulting numbers:

Bash
cd ~/insets-demo
cat > src/components/DetailsScreen.test.tsx <<'TSX'
import { render, screen } from '@testing-library/react-native'
import { StyleSheet } from 'react-native'
import { onPhone, phones } from '../testing/phones'
import { DetailsScreen } from './DetailsScreen'

test('pads the top and sides, and leaves the bottom to the scroll content', async () => {
  await render(<DetailsScreen onBack={jest.fn()} />, { wrapper: onPhone(phones.iphonePortrait) })

  expect(screen.getByTestId('details-screen')).toHaveProp('edges', {
    top: 'additive',
    right: 'additive',
    bottom: 'off',
    left: 'additive',
  })
  const form = screen.getByTestId('details-form')
  expect(StyleSheet.flatten(form.props.contentContainerStyle)).toMatchObject({ paddingBottom: 58 })
})

test('labels every field', async () => {
  await render(<DetailsScreen onBack={jest.fn()} />, { wrapper: onPhone(phones.androidThreeButton) })

  for (const label of ['Full name', 'Phone number', 'Delivery address', 'Landmark or directions', 'Notes for the pharmacist']) {
    expect(screen.getByLabelText(label)).toBeOnTheScreen()
  }
})
TSX
npx jest src/components/DetailsScreen --ci

Check it worked

Jest reports Tests: 2 passed, 2 total. The bottom padding of the form content is 58 on the iPhone: 34 for the home indicator plus your 24.

Step 7 · Wire up the app, allow landscape and build it

The insets and the keyboard state both come from providers. Put SafeAreaProvider and KeyboardProvider at the very top of the app, once. Replace the template's App.tsx:

Bash
cd ~/insets-demo
cat > App.tsx <<'TSX'
import { StatusBar } from 'expo-status-bar'
import { useState } from 'react'
import { KeyboardProvider } from 'react-native-keyboard-controller'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import { ChatScreen } from './src/components/ChatScreen'
import { DetailsScreen } from './src/components/DetailsScreen'

export default function App() {
  const [screen, setScreen] = useState<'chat' | 'details'>('chat')

  return (
    <SafeAreaProvider>
      <KeyboardProvider>
        <StatusBar style={screen === 'chat' ? 'light' : 'dark'} />
        {screen === 'chat' ? (
          <ChatScreen onOpenDetails={() => setScreen('details')} />
        ) : (
          <DetailsScreen onBack={() => setScreen('chat')} />
        )}
      </KeyboardProvider>
    </SafeAreaProvider>
  )
}
TSX

The status bar text is light over the dark chat header and dark over the white form. With edge-to-edge, your header is the status bar's background, so its text colour is your choice to get right.

The blank template locks the app to portrait. Allow both orientations, and give the app an Android package name so you can generate the native project. Replace com.example.insetsdemo with your own reverse-domain name:

Bash
cd ~/insets-demo
node -e "const fs=require('fs');const c=JSON.parse(fs.readFileSync('app.json','utf8'));c.expo.orientation='default';c.expo.android={...c.expo.android,package:'com.example.insetsdemo'};fs.writeFileSync('app.json',JSON.stringify(c,null,2)+'\n')"
npx expo config --type public --json | node -e "const c=JSON.parse(require('fs').readFileSync(0,'utf8')); console.log(c.orientation, c.android.package)"

That prints default com.example.insetsdemo. Now bundle the app for Android, which compiles every file and fails on a bad import:

Bash
cd ~/insets-demo
npx expo export --platform android
grep -a -c "Write a message" dist/_expo/static/js/android/*.hbc

Finally, generate the Android project without installing anything and ask Expo's autolinking which native libraries the build will include:

Bash
cd ~/insets-demo
npx expo prebuild --platform android --no-install
npx expo-modules-autolinking react-native-config --platform android --json > autolinking.json
node -e "const d=require('./autolinking.json').dependencies; console.log(Object.keys(d).filter(n => /safe-area|keyboard|reanimated|worklets/.test(n)).sort().join(' '))"
rm autolinking.json

Neither library adds anything to app.json: they have no config plugin and need no native settings. Autolinking finds them in package.json.

Check it worked

The export ends without errors and the grep prints 1 or more, so the composer's placeholder is in the Android bundle. The last command prints react-native-keyboard-controller react-native-reanimated react-native-safe-area-context react-native-worklets. Run the whole suite once more:

Bash
cd ~/insets-demo
npx jest --ci

Jest reports five test suites with Tests: 12 passed, 12 total.

Step 8 · Check it on phones, in both orientations

Tests prove the numbers. Only a phone shows whether the result feels right. Start the development server and open the app in Expo Go, which includes both libraries:

Bash
cd ~/insets-demo
npx expo start

Scan the QR code with Expo Go on Android or the Camera app on iOS, or press a or i to open an Android emulator or the iOS Simulator. Then work through this list on each device you have:

  • Top edge. The dark header runs to the very top of the screen, and the title starts below the clock, the camera cut-out or the Dynamic Island.
  • Bottom edge, keyboard closed. On an iPhone without a home button, the message box sits just above the home indicator. On Android, switch between gesture navigation and three-button navigation in the system settings (usually under System or Display) and check the box clears the bar in both.
  • Keyboard open. Tap the message box. It rises with the keyboard and rests on top of it with a small gap, not a gap the height of the home indicator.
  • Dismissal. With the keyboard up, drag the conversation down. On iOS the keyboard follows your finger; on Android it closes as the scroll starts.
  • The form. Open Your details, tap Notes for the pharmacist, and check the page scrolls the field above the keyboard with space to spare.
  • Landscape. Rotate the phone, or rotate the simulator or emulator from its toolbar or menu. The header title and the message box move in from the notch side, and nothing sits under the camera.
A phone on its side. Grey bands of 59 points on the left and right mark the side insets, with the camera cut-out on the left. The Messages header and the message box start inside the bands, the top inset is 0 and a 21-point band sits along the bottom above the home indicator.
In landscape the insets move to the sides.

If you test on a low-cost Android phone, watch the keyboard animation too. The keyboard library drives it on the UI thread with Reanimated, so it stays smooth even when the JavaScript thread is busy.

Check it worked

Every item on the list passes on at least one iPhone with a notch or Dynamic Island (a simulator counts) and one Android phone or emulator. If the message box hides behind the keyboard on Android only, check that KeyboardProvider wraps the whole app in App.tsx.

When you are finished, delete the practice folder:

Bash
rm -rf ~/insets-demo

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.