Instructor: We have a text field on the bottom half of the screen, and when it's selected, the on-screen keyboard pops up and covers the text field. To make the text field automatically move up and out of the way of the keyboard, import KeyboardAvoidingView from React Native.
Then wrap the entire screen with a KeyboardAvoidingView component. The KeyboardAvoidingView will automatically move components around on the screen in order to avoid the keyboard, but we have to specify how we want the components to move around before it will do anything.
First, make sure it fills the entire screen by setting a flex one style prop. Then we'll replace the main container view with a scroll view to allow the view to scroll properly under the keyboard. This isn't always necessary. It depends on the styling and content of your component. It will help in this case.
Then we have to specify a behavior for how the components will adjust when the keyboard appears on screen. The options are height, position, and padding. Each behavior acts differently. Test out how each option affects the components for your screen.
We'll use the padding behavior here, which will adjust the components to avoid the keyboard on the screen. Also note that this may behave differently on iOS and Android, so it's important to test on both. Finally, we'll enable the avoiding view by setting the enabled prop to true.
Now, when we reload the app and select a text input, the view moves up and out of the way, so the text input stays out from under the keyboard. The user can also scroll the scroll view up and down to access the other text field and the button.
The keyboard avoiding scroll view can be a bit particular. It also has the ability to change the padding and spacing of your components. If we want to avoid that, we can use a module called keyboard-aware-scroll-view. Install the library with npm install save react-native-keyboard-aware-scroll-view.
Then import the keyboard aware scroll view in the screen. Now, instead of the keyboard avoiding view, wrap the entire screen in the keyboard aware scroll view. We don't need the behavior or enabled prop for this component, but keep the flex style to be sure that the view takes up the entire screen.
We also don't need the scroll view anymore, because the keyboard aware scroll view will put that in for us. When we run that, the view automatically scrolls up and out of the way without changing the margin or padding of any of the components. The user can still scroll up and down to see the other components on the screen.