How to use form with keyboard without bug

The simplest way to create a form that doesn't get overflowed by the keyboard is to use the <KeyboardAvoidingView> component from react-native. Inside of it, we will have the <TouchableWithoutFeedback> component, also from react-native, that will allow users to close the keyboard by touching anywhere in the page.

We will add this property : behavior={Platform.OS === 'ios' ? 'padding' : 'height'} to the <KeyboardAvoidingView> component so the behavior of the keyboard adapts to the OS the user has. And also this property : onPress={Keyboard.dismiss} to the <TouchableWithoutFeedback> component so it actually does something when we click in the page.

After this, we will add some style on the <KeyboardAvoidingView> component. If the content of the page is not centered in the screen, the keyboard will not 'push' the content up. To prevent this behavior, we need to add 2 style properties : style={{ flex: 1, justifyContent: 'center' }}. With this style, the page will be centered in the screen and will allow the component to push the content up when the keyboard shows up.

The last thing we will do, is add a <View></View> that will contain the whole page.

The final result of the setup should look like this :

<KeyboardAvoidingView
    behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    style={{ flex: 1, justifyContent: 'center' }}
>
    <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <View>
            {...} // Your page here
        </View>
    </TouchableWithoutFeedback>
</KeyboardAvoidingView>

Notes

If after this setup, your keyboard still overflows a little your content, you can add a property to the <KeyboardAvoidingView> component, called keyboardVerticalOffset. It takes a number as a value and will increase the space between the content and the keyboard so everything works as you intended.

All the elements used in this example are imported from react-native (even Platform and Keyboard).

Last updated