← Back to Chapters

Keyboard Handling in React Native

⌨️ Keyboard Handling in React Native

? Quick Overview

Keyboard handling in React Native is essential when building forms or input-heavy screens. Without proper handling, the on-screen keyboard may cover input fields, buttons, or important UI elements. React Native provides built-in components to manage keyboard behavior smoothly across Android and iOS.

? Key Concepts

  • KeyboardAvoidingView – Automatically moves UI when keyboard appears
  • ScrollView – Enables scrolling when content is hidden by keyboard
  • Keyboard API – Listens to keyboard show/hide events
  • Platform – Handles platform-specific behavior

? Syntax / Theory

The most common approach is wrapping your screen or form inside a KeyboardAvoidingView. This component adjusts its layout based on the keyboard visibility. On iOS, padding behavior is commonly used, while Android often works well with height adjustment.

? Code Example(s)

? View Code Example
// Basic keyboard handling using KeyboardAvoidingView
import React from "react";
import { View, TextInput, Button, KeyboardAvoidingView, Platform } from "react-native";

export default function App() {
  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === "ios" ? "padding" : "height"}
      style={{ flex: 1, justifyContent: "center", padding: 20 }}
    >
      <TextInput
        placeholder="Enter username"
        style={{ borderWidth: 1, marginBottom: 12, padding: 10 }}
      />
      <TextInput
        placeholder="Enter password"
        secureTextEntry
        style={{ borderWidth: 1, marginBottom: 12, padding: 10 }}
      />
      <Button title="Login" onPress={() => {}} />
    </KeyboardAvoidingView>
  );
}

? Live Output / Explanation

What Happens?

  • When the keyboard opens, inputs are pushed upward
  • The focused input stays visible
  • User can continue typing without UI overlap

? Interactive Simulator

Click the input field in the phone to see how the keyboard affects the layout.

My App
Please login below ?
Don't let the keyboard hide me!
User: Okay!
Tap here to type...
 
 
 
 
 
 
 
 
 
 
 
 
Status: Keyboard Hidden

? Interactive Concept (Visual Flow)

⬇️ Normal Screen
⬆️ Keyboard Appears
? KeyboardAvoidingView adjusts layout automatically

? Use Cases

  • Login and signup screens
  • Chat applications
  • Forms with multiple inputs
  • Search bars and comment sections

? Tips & Best Practices

  • Always test on both Android and iOS
  • Combine KeyboardAvoidingView with ScrollView for long forms
  • Avoid fixed heights when keyboard is involved
  • Use keyboardShouldPersistTaps="handled" in ScrollView

? Try It Yourself

  • Add a third input field and test keyboard behavior
  • Wrap inputs in ScrollView and observe differences
  • Listen to keyboard events using the Keyboard API
  • Experiment with different behavior values