React Native KeyboardAvoidingView explanation with example

Introduction :

One of the most common problem that we face while developing react native apps is the keyboard hide the text input when you click on it. For example :

ios keyboard problemI am clicking on the TextInput and the keyboard appeared over it. This is the problem

There are different ways to solve it. One of the easiest ways is to use KeyboardAvoidingView that you will get with the react-native package. It automatically adjusts the bottom padding of the view based on the keyboard position.

In this post, I will show you how to use KeyboardAvoidingView with a simple example.

KeyboardAvoidingView :

KeyboardAvoidingView comes with the react-native package. If we wrap all other components inside it, it will move the components once the keyboard appears. For the above example, after adding KeyboardAvoidingView, it will give the following result :

ios keyboardavoidingview

Full code :

import React from 'react';
import {
  SafeAreaView,
  StatusBar,
  StyleSheet,
  Platform,
  KeyboardAvoidingView,
  TextInput,
} from 'react-native';

const App = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <KeyboardAvoidingView
        behavior={Platform.Os == 'ios' ? 'padding' : 'height'}
        style={styles.container}>
        <SafeAreaView>
          <TextInput style={styles.textInput} />
        </SafeAreaView>
      </KeyboardAvoidingView>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'flex-end',
  },
  image: {
    height: 400,
    width: 400,
  },
  textInput: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    margin: 30,
  },
});

export default App;

Props :

Following are the props it accepts :

1. behavior :

Android and iOS react differently to this props. It takes one of the following enums :

height, position and padding

2. contentContainerStyle :

style of the content container.

3. enabled :

enable or disable this component. The default is true.

4. keyboardVerticalOffset :

The default is zero. This is the distance from the top of the screen to the react-native view. You can set one number to it.