Lesson 3 of 9
Keyboard Handling - KeyboardAvoidingView
The on-screen keyboard covers ~40% of the screen on a phone. Without proper keyboard handling, inputs at the bottom of the form are hidden when the keyboard appears. KeyboardAvoidingView is native; react-native-keyboard-controller is the enhanced production solution.
KeyboardAvoidingView Patterns
import { KeyboardAvoidingView, Platform, ScrollView, View } from 'react-native';
// ---- Standard setup ----
function FormScreen() {
return (
<KeyboardAvoidingView
style={{ flex: 1 }}
// iOS: 'padding' adds bottom padding equal to keyboard height
// Android: 'height' shrinks the KeyboardAvoidingView's height
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
// Offset for header height (React Navigation header = ~44px on iOS)
keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
>
<ScrollView
contentContainerStyle={{ flexGrow: 1, padding: 24 }}
// 'handled': taps pass through to Pressables even when inside scrollview
// prevents double-tap needed to submit button when keyboard is open
keyboardShouldPersistTaps="handled"
// Don't dismiss keyboard when scrolling (smoother)
keyboardDismissMode="none"
>
{/* Form content */}
</ScrollView>
</KeyboardAvoidingView>
);
}
// ---- Programmatic keyboard dismiss ----
import { Keyboard } from 'react-native';
// Dismiss on press outside inputs
<Pressable onPress={Keyboard.dismiss} style={{ flex: 1 }}>
<Form />
</Pressable>
// ---- Listen to keyboard events (for custom animations) ----
import { Keyboard, Animated } from 'react-native';
const translateY = new Animated.Value(0);
Keyboard.addListener('keyboardWillShow', (e) => {
Animated.timing(translateY, {
toValue: -e.endCoordinates.height / 2,
duration: e.duration,
useNativeDriver: true,
}).start();
});Tip
Tip
Practice Keyboard Handling KeyboardAvoidingView in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Preventing soft keyboard overlap across iOS padding and Android height behaviors
Practice Task
Note
Practice Task - (1) Write a working example of Keyboard Handling KeyboardAvoidingView from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Keyboard Handling KeyboardAvoidingView is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.
Finished this lesson?