KeyboardAvoidingView

KeyboardAvoidingView: Fix in React Native (expo)

Introduction

I am currently developing a todo app using react native and expo. While I was working on my login screen, I saw that the native keyboard is overlapping the input fields and the user won’t be able to see what he/she is typing. In order to resolve this issue, React Native has provided the KeyboardAvoidingView component in which the whole screen UI is wrapped. Find the documentation here. Unfortunately, when I implemented it, It was not working as expected but I did manage to find the workaround.

What is the issue faced?

So in the expo, Even if you have added KeyboardAvoidingView as shown in documentation it doesn’t seem to work. I tried switching behavior property from “padding ” to “height” and the other way around as someone in the Github issues said that made it work for android but was of no use. There was another solution stating, if we add KeyboardVerticalOffset to a higher value, it will be fixed but even that didn’t work.

Finally, After searching for half an hour I did find the workaround.

How to fix it?

In order to make the KeyboardAvoidingView work properly in Expo, you have to make sure of the following things:

  • Wrap the UI inside a ScrollView component
  • update status bar styles in app.json (old Approach) OR
  • Wrap the ScrollView inside the SafeAreaView Component (Better Approach) – thanks for the info, Sapan Kumar Das

Refer the following Gist to make the changes mentioned above:

import {KeyboardAvoidingView, ScrollView, Platform} from 'react-native';
export default class App extends Component{
render(){
return(
<SafeAreaView>
<KeyboardAvoidingView behavior={Platform.Os == "ios" ? "padding" : "height" } enabled>
<ScrollView>
/* add your Screen Ui Components here */
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
}
view raw App.js hosted with ❤ by GitHub
{
expo: {
...
"androidStatusBar": {
"backgroundColor": "#A17EEB"
},
android: {
...
}
}
}
//make sure you add it outside the android key
view raw app.json hosted with ❤ by GitHub

Conclusion

Once the changes are made, Restart the bundler and load the app in your expo app and you will see that it is working as expected. Check the demo below:

If you have any queries, Let me know in the comments section below:

40
40