Kinda Code
Home/React Native/React Native: KeyboardAvoidingView example

React Native: KeyboardAvoidingView example

Last updated: February 22, 2022

KeyboardAvoidingView is a core component in React Native. This component makes sure the virtual keyboard will never cover the TextInput component so that your user can type without annoyance.

The Example

Without KeyboardAvodingView, a TextInput might be overlapped by the soft keyboard if it stays near the bottom of the screen:

With KeyboardAvoidingView, the TextInput will be pushed up (like the water lifts a ship) when the soft keyboard appears:

The code

Import the KeyboardAvodingView component and use it to wrap your JSX code:

import React from "react";
import {
  StyleSheet,
  View,
  KeyboardAvoidingView,
  TextInput,
} from "react-native";

const App = () => {
  return (
    <KeyboardAvoidingView
      behavior={Platform.OS == "ios" ? "padding" : "height"}
      style={styles.wrapper}
    >
      <View style={styles.screen}>
        <TextInput
          style={styles.textInput}
          placeholder="Enter something here"
        />
      </View>
    </KeyboardAvoidingView>
  );
};

// just some styles for our app
const styles = StyleSheet.create({
  wrapper: {
    flex: 1,
  },
  screen: {
    flex: 1,
    justifyContent: "flex-end",
    alignItems: "center",
    backgroundColor: "#4066a3",
  },
  textInput: {
    backgroundColor: "#fff",
    marginBottom: 60,
    borderWidth: 1,
    borderColor: "#999",
    padding: 15,
    height: 40,
    width: 300,
  },
});

export default App;

Further reading:

You can also check our React topic page and React Native topic page for the latest tutorials and examples.

Related Articles