KeyboardAvoidingView not working properly? Check your Flexbox Layout first

KeyboardAvoidingView not working properly? Check your Flexbox Layout first

Image for post

Keyboard overlaying Input or Submit button is a common problem in React Native. Something like this:

Image for post

Here?s the code:

And we found there is a built-in component called KeyboardAvoidingView. Terrific! This is exactly what we need! Let?s add it right now:

<KeyboardAvoidingView behavior={Platform.OS === “ios” ? “padding” : null} style={{ flex: 1 }}> {/* Code from above */}</KeyboardAvoidingView>

Hmm? wait a minute, why doesn?t my KeyboardAvoidingView seem to be working at all?

Image for post

Okay, let?s hold on and have a look again what is KeyboardAvoidingView (https://facebook.github.io/react-native/docs/keyboardavoidingview)

It can automatically adjust either its position or bottom padding based on the position of the keyboard.

In other words, KeyboardAvoidingView is just a normal <View /> component with paddingBottom.

So in order for us to better understand the current issue, let?s simulate our React Native screen with HTML and CSS:

We can simulate the Keyboard toggle by changing paddingBottom from 300 to 0

As we can see, the exact same issue happened again. Items overflow the container instead of being pushed out of the container. This is because Flexbox has default justifyContent as flex-start, which means items are positioned from the beginning(top) of the container.

Therefore, as long as we set justifyContent to be flex-end, bottom will become the beginning of the container, items then will be pushed out from the top.

Image for post

Now the overflow issue has been fixed, but adding flex-end makes the content stay at the bottom of the container. We can solve this by adding a <div style={{ flex: 1 }} /> by the end of the container to take up the empty spacing.

Image for post

Great! We can now do the same to our React Native code. Here?s the final code.

Image for post

28