'React Native KeyboardAvoidingView not working properly after orientation changes
while trying out KeyboardAvoidingView with the Expo Go app and npm create-react-native-app
on Android I noticed a weird behaviour after a device rotation.
- When I launch the app in portrait mode and then switch to landscape the KeyboardAvoidingView cycles between not getting pushed up at all or not getting pushed up enough when tapping the TextInput. Also, when hiding the keyboard the button stays hidden every second time.
- When I launch the app in landscape mode and then switch to portrait the KeyboardAvoidingView always gets pushed up way to much.
Here is a short clip showing what happens: KeyboardAvoidingView and rotating device
How can one prevent this from happening?
Here is the code I used for create-react-native-app
(I only changed the name of the component):
import React from 'react';
import {
View,
KeyboardAvoidingView,
TextInput,
StyleSheet,
Text,
Platform,
TouchableWithoutFeedback,
Button,
Keyboard,
} from 'react-native';
const App = () => {
return (
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={styles.container}>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.inner}>
<Text style={styles.header}>Header</Text>
<TextInput placeholder="Username" style={styles.textInput} />
<View style={styles.btnContainer}>
<Button title="Submit" onPress={() => null} />
</View>
</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
inner: {
padding: 24,
flex: 1,
justifyContent: 'space-around',
},
header: {
fontSize: 36,
marginBottom: 48,
},
textInput: {
height: 40,
borderColor: '#000000',
borderBottomWidth: 1,
marginBottom: 36,
},
btnContainer: {
backgroundColor: 'white',
marginTop: 12,
},
});
export default App;
Solution 1:[1]
Adding keyboardVerticalOffset="-999999"
fixed the issue for me.
It seems that after rotating the device the height of the keyboard in landscape- and portraitmode are added/subtracted from each other, leading to this weird behaviour.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | gilex |