DEV Community

loading...

How to fix KeyboardAvoidingView in React Native?

chakrihacker profile image Subramanya Chakravarthy ใƒปUpdated on ใƒป1 min read

Hey ๐Ÿ‘‹

Update: 8th April 2020

If you are using React navigation V5 then use

import { HeaderHeightContext } from "@react-navigation/stack";
<HeaderHeightContext.Consumer>
  {headerHeight => (
     <KeyboardAvoidingView
    {...(Platform.OS === "ios" ? { behavior: "padding" } : {})}
     // you might need sometimes๐Ÿ‘‡
    contentContainerStyle={{flex: 1}}
    // chances are you might be using react-navigation
    // if so ๐Ÿ‘‡
    keyboardVerticalOffset={headerHeight + 64}
    // You can import Header Component from react-navigation and it has height attached to it
    // 64 is some extra padding, I feel good, feel free to tweak it
>
    {children}
</KeyboardAvoidingView>
   )}
</HeaderHeightContext.Consumer>

End of update

Here's how I use KeyboardAvoidingView, this will be the root component for the screen

<KeyboardAvoidingView
    {...(Platform.OS === "ios" ? { behavior: "padding" } : {})}
     // you might need sometimes๐Ÿ‘‡
    contentContainerStyle={{flex: 1}}
    // chances are you might be using react-navigation
    // if so ๐Ÿ‘‡
    keyboardVerticalOffset={Header.HEIGHT + 64}
    // You can import Header Component from react-navigation and it has height attached to it
    // 64 is some extra padding, I feel good, feel free to tweak it
>
    {children}
</KeyboardAvoidingView>

If you are still facing problems, try to understand where KeyboardAvoidingView Component is from top of the screen and then adjust keyboardVerticalOffset based on that. That's the key to fix it

Discussion

pic
Editor guide
Collapse
rodakd profile image
Dawid Rodak

If you're using React Navigation 5 you can use useHeaderHeight hook from @react-navigation/stack.

Collapse
chakrihacker profile image
Subramanya Chakravarthy Author

Yes, thanks for the suggestion