height vs position vs padding in KeyboardAvoidingView "behavior"
I agree that the lack of documentation here is frustrating. If you dig into the source code for KeyboardAvoidingView
, you will find a switch around the behavior
: https://github.com/facebook/react-native/blob/92073d4a71d50a1ed80cf9cb063a6144fcc8cf19/Libraries/Components/Keyboard/KeyboardAvoidingView.js#L157
It looks like the following is happening:
height
A <View>
is returned with styling that attempts to set a static height to the view that is either the screen height, or the screen height minus the keyboard when the keyboard is present.
position
A nested <View>
is returned, where the outer View has your styles applied, and the inner View has a bottom
style applied that attempts to match the keyboard height when the keyboard is present.
padding
A single <View>
is returned where a paddingBottom
style is applied to the height of the keyboard if the keyboard is present.
Given the arbitrary options available, it looks like when using the KeyboardAvoidingView
you should exercise trial and error, and check both devices for your desired outcome. In theory all three options should work, but as the docs say there is some nuance between device types.
In my opinion, this component should be scrapped though, in favour of helper functions that would return keyboard heights over time, so you could apply your own style ideas directly based on keyboard visibility.
Allow me to go through these attributes for the prop behavior one by one.
I am considering the <TextInput>
object for which our keyboard gets called.
- "padding": The component goes to a higher position once the keyboard pops up. It is advised to use padding when there are not many components on the screen otherwise the layout might break where the Component may overlap with the components above it.(note: the components above it would also be moved up..but in order to adjust the Views there might be an overlap). Note: Here Both things : the TextInput and the components may get overlapped.
- "position": the entire View containing TextInput would be moved up and there is a chance that some of the components above may not be available/visible on the top of the screen i.e. would be cut off from the top of the screen being the upper bound.
- "height": generally used with keyboardVerticalOffset. It is used to resize the View of the screen once the keyboard pops up. Might as well lead to overlapping in an attempt to resize the screen. Here, the TextInput would be overlapping above the component above it in case of an overlap.
**Note: when we are wrapping ou screen inside a ScrollView make sure to wrap the ScrollView with <KeyboardAvoidingView style={{flex:1}} ...> where flex:1 should be used to occupy the entire component as ScrollView is wrapping the Component **