Atom Lab logo

How to prevent keyboard covering a text input in React Native

Request, Deliver, Revise, Done

Get unlimited UI Design & React Development for a fixed monthly price

50% off your first month

The Problem

A common problem you might encounter when working with React Native is that the keyboard will often cover text inputs when focused. See the image below for an example:

By default a View will not adjust the viewport when the virtual keyboard is triggered due to an input being focused. This obviously isn't ideal - so how can we fix it? Enter KeyboardAvoidingView.

Using KeyboardAvoidingView to adjust screen to the virtual keyboard

KeyboardAvoidingView is a core React Native component that allows us to adjust views to account for the virtual keyboard. When accounting for the keyboard height, KeyboardAvoidingView can automatically adjust either it's height, position or bottom padding based on the height of the keyboard. Let's see how it works:

import React from "react"; import { View, Text, TextInput, StyleSheet } from "react-native"; const KeyboardAvoidingViewExample = () => { return ( <View style={styles.containerStyle}> <View style={styles.fieldStyle}> <Text style={styles.labelStyle}>First Name</Text> <TextInput value="Joe" style={styles.inputStyle} /> </View> <View style={styles.fieldStyle}> <Text style={styles.labelStyle}>Surname</Text> <TextInput value="Bloggs" style={styles.inputStyle} /> </View> <View style={styles.fieldStyle}> <Text style={styles.labelStyle}>Email</Text> <TextInput value="" style={styles.inputStyle} /> </View> </View> ); }; const styles = StyleSheet.create({ containerStyle: { display: "flex", flex: 1, flexDirection: "column", justifyContent: "center", width: "100%", padding: 20, }, fieldStyle: { display: "flex", flexDirection: "column", marginBottom: 28, }, labelStyle: { marginBottom: 8, fontSize: 18, }, inputStyle: { borderColor: "#ccc", borderWidth: 1, borderRadius: 4, padding: 8, }, }); export default KeyboardAvoidingViewExample;

Copyright 2024 - Atom Lab | Privacy Policy | Terms and Conditions