← Back to Chapters

KeyboardAvoidingView

⌨️ KeyboardAvoidingView

? Quick Overview

KeyboardAvoidingView is a built-in React Native component used to automatically adjust the layout when the on-screen keyboard appears. It prevents important UI elements like TextInput and buttons from being hidden by the keyboard, especially on mobile devices.

? Key Concepts

  • Automatically moves UI when keyboard opens
  • Works differently on iOS and Android
  • Commonly wraps forms and input screens
  • Uses behavior prop to control movement

? Syntax / Theory

KeyboardAvoidingView adjusts its children based on keyboard visibility. The behavior prop defines how the view responds, such as shifting position, adding padding, or resizing height.

? View Code Example
// Import KeyboardAvoidingView from react-native
import { KeyboardAvoidingView, Platform, TextInput, View } from "react-native";

export default function App() {
  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === "ios" ? "padding" : "height"}
      style={{ flex: 1 }}
    >
      <View style={{ padding: 20 }}>
        <TextInput placeholder="Enter name" />
      </View>
    </KeyboardAvoidingView>
  );
}

?️ Live Output / Explanation

What Happens?

When the keyboard opens, the entire view shifts upward. On iOS, padding is added below the content, while on Android the height of the view is adjusted automatically.

? Interactive Visualization

Use the simulator below to understand why KeyboardAvoidingView is necessary. Click the input field inside the phone to trigger the keyboard.

My App
Hey! How does this work?
The keyboard usually covers the input.
That's annoying.
Using KeyboardAvoidingView fixes it!
⌨️ Virtual Keyboard
(Click here to close)

Status: KeyboardAvoidingView Active. The layout resizes so the input stays visible.

? View Conceptual Diagram
// Pseudo-layout representation for understanding behavior
[Screen]
[Input Field]
[Button]
------ Keyboard Appears ------
[Input Field]
[Button]
[Keyboard]

? Use Cases

  • Login and signup screens
  • Chat applications
  • Forms with multiple inputs
  • Payment and checkout pages

✅ Tips & Best Practices

  • Always combine with Platform.OS for best behavior
  • Use flex: 1 on KeyboardAvoidingView
  • Avoid nesting multiple KeyboardAvoidingView components
  • Test on both Android and iOS devices

? Try It Yourself

  • Create a screen with multiple TextInput fields
  • Wrap the screen in KeyboardAvoidingView
  • Change behavior between padding and height
  • Observe the difference on Android vs iOS