tezvyn:

KeyboardAvoidingView: Keep Inputs Visible When Keyboard Appears

AI-drafted, machine-checkedSource: reactnative.devintermediate

KeyboardAvoidingView prevents the on-screen keyboard from hiding your inputs. It's a wrapper that shrinks, slides, or pads its content to keep it in view. Use it for login forms or chat windows. The `behavior` prop acts differently on iOS vs. Android.

WHY IT EXISTS: On mobile, the virtual keyboard takes up significant screen space. Without intervention, it can cover the very text input the user is trying to type into, creating a frustrating user experience. KeyboardAvoidingView was created to solve this common mobile UI problem directly within React Native.

THE MENTAL MODEL: Think of KeyboardAvoidingView as an intelligent container that watches for the keyboard. When the keyboard shows up, the container gets out of the way by either resizing itself, repositioning its contents, or adding padding to its bottom, ensuring its children remain visible and accessible.

HOW IT WORKS: You wrap the part of your UI that needs to avoid the keyboard (like a form) with this component. You then configure its behavior prop. The three main behaviors are 'padding' (adds bottom padding to the view), 'height' (reduces the component's height by the keyboard's height), and 'position' (repositions the view's y-coordinate). The component listens for keyboard events and applies the chosen transformation.

WHEN TO USE IT: Use it on any screen containing TextInput components, particularly when those inputs are near the bottom of the screen. It is crucial for login forms, chat screens, and any data entry view to maintain usability. You can also use the keyboardVerticalOffset prop to add extra space if you have a header or tab bar.

WHEN NOT TO USE IT: Avoid wrapping your entire application in a single KeyboardAvoidingView; it's meant for specific views that contain inputs. The behavior prop acts differently on iOS and Android, which is a major footgun. 'padding' is often a safe bet for iOS, while Android might not need it or might work better with other solutions like setting windowSoftInputMode in AndroidManifest.xml. Always test on both platforms.

ONE CANONICAL EXAMPLE: A login screen has a View containing two TextInput fields and a Button. To prevent the keyboard from covering the password field when the user focuses the email field, you wrap the container View in <KeyboardAvoidingView behavior="padding">. This adds padding to the bottom of the view, pushing all its content up and out of the way of the keyboard.

Read the original → reactnative.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.