In this lesson, you will learn how to prevent your UI from being hidden behind the software keyboard by dynamically adjusting your layout when the keyboard appears.
The Keyboard Obstacle
When a user taps an TextInput, the native software keyboard slides up from the bottom of the screen. Because the keyboard occupies a significant portion of the viewport, it often obscures input fields or submit buttons located near the bottom of your screen. This "clipping" creates a poor user experience because the user can no longer see what they are typing or interact with the elements needed to proceed.
The Strategy: Dynamic Shifting
To solve this, your layout needs to respond to the keyboard’s presence. Instead of letting the keyboard overlay your content, you must inform your layout engine that the available screen space has effectively shrunk.
The most efficient way to manage this in React Native is by using a KeyboardAvoidingView. This component acts as a wrapper that automatically shifts its internal children upward when the keyboard is triggered.
Implementation Example
Consider a login screen with a button fixed to the bottom:
import { KeyboardAvoidingView, TextInput, Button, Platform } from 'react-native';
const LoginScreen = () => {
return (
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={{ flex: 1 }}
>
<TextInput placeholder="Enter username" />
<Button title="Submit" onPress={() => {}} />
</KeyboardAvoidingView>
);
};
Here, the behavior property tells the layout engine how to react:
paddingadds extra space to the bottom of the view to push content up.heightadjusts the height of the view itself.
By wrapping your layout in this component, the Flexbox engine recalculates the available space. Because your Flexbox containers are fluid (using flex: 1 or space distribution), they gracefully contract, ensuring that your TextInput and Button remain visible to the user regardless of whether the keyboard is present or hidden.
Key Takeaway: Use KeyboardAvoidingView to wrap your input-heavy layouts so the layout engine can dynamically recalculate space and shift content away from the encroaching software keyboard.