Welcome back to another hackajob #techtutorial. This week, we’re going to be learning how to use the ‘KeyboardAvoidingView’. If you’ve been using React Native for some time, you may have faced the following situation:
Sometimes you'll working on an app and realise that whilst you’ve done a lot of work, Android has native behaviours that don’t cover input fields with the keyboard and you’ll need to use something called the 'Keyboard Avoiding View' for iOS. In today’s tutorial, we’ll be showing you 3 ways to implement the 'KeyboardAvoidingView'.
For use in padding behaviour, the 'KeyboardAvoidingView' component will be placed in the higher position. You can use it after the safe area view:
Above is an example of the basic implementation. If you don’t have a lot of information on your screen then padding is likely to be the best choice because the whole screen is available to view, regardless of whether every view is resized or not. However, if you have text fields with accompanying images and certain views at fixed sizes, your layout could break, meaning that padding isn’t always the best choice:
When using the position option, the entire view will be moved ‘up’. Note that in this case, some of the information at the top of the screen won’t be available:
In the example above, we’re using ‘dimensions’ to get the width within the view inside the ‘KeyboardAvoidingView’ component.
An example of Position Behaviour:
The last behaviour that we can take a look at is height. Obviously different from the concept of padding, height behaviour will resize the view on the screen after the keyboard pop up. To use height, the component should be placed at the start of the high order view after the resize of ‘KeyboardAvoidingView’. You’ll also need a little help from the ‘KeyboardVerticalOffset’ props too:
Even with all of the changes made above, when you have that much information on your screen, the height behaviour won’t be able to render properly on your screen:
The official documentation recommends not using any props for Android, however you can get around this by using the little trick below:
When using ‘KeyboardAvoidingView’, our first choice is always padding (particularly if you don’t have many components in the screen, so remember to always test with smaller screens). If you choose to use more than one input field and all the other fields are not viewable on the screen, you can always use the ‘ScrollView’ component so that the user can roll the screen whilst the keyboard is still active. Remember that the height component requires a few more settings, so whilst it can be useful, we’d recommend making sure to do plenty of testing.