Understanding KeyboardAvoidingView

Óliver L. Sanz
2 min readApr 22, 2021

The last couple of days I’ve been struggling with React Native’s KeyboardAvoidingView. After reading multiple times the (too brief) documentation, some googling and a lot of trial and error now I finally understand how it works. I’m writing this so I won’t forget it!

The official documentation says:

“It is a component to solve the common problem of views that need to move out of the way of the virtual keyboard. It can automatically adjust either its height, position, or bottom padding based on the keyboard height.”

So, what I have to do with it? Do I use it to wrap my text inputs? Do I put it below them? What black magic powers it?

No black magic indeed! It is as simple as this:

  • Just wrap your entire screen on the KeyboardAvoidingView.
  • It will behave as a normal view when the keyboard is hidden.
  • When the keyboard is out the KeyboardAvoidingView will shrink, filling just the space it has between the top of the screen and the top of the keyboard.
  • Consider wrapping some of your components on a ScrollWiew. It is a normal practice when the content of the screen can overflow its size. And with a screen taken up by the keyboard that is likely the case.

So, when using the KeyboardAvoidingView just wrap the entire screen with it. When laying out the rest of the components, just have in mind that the whole screen will effectively “shrink” when the keyboard comes out. That’s all.

There are some common misunderstandings about this component:

  • “You need to have justifyContent: ‘flex-end’ in your main view so that its child components go up when the keyboard shows”. False! If you need this to make it work, it means that there is something else wrong in your code. Just refactor following the key points I’ve given and you won’t need the flex-end.
  • “You just have to wrap the specific input that you want to keep above of the keyboard”. False! It will mess up the whole component, as it assumes it is taking up all the screen size, not only wrapping one component.

I leave you below a little snack taken from the documentation, so you can see how it works and experiment with it:

--

--