DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on • Updated on

How to fix KeyboardAvoidingView in React Native?

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 (4)

Collapse
256hz profile image
Abe Dolinger • Edited on

instead of
{...(Platform.OS === "ios" ? { behavior: "padding" } : {})}
I recommend
behavior={Platform.select({ ios: 'padding' })}
this will also evaluate to undefined on Android.

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

Collapse
guptavishesh143 profile image
Vishesh Gupta

Guys Check this Example,

Its 100% solution for Android and Ios.

github.com/guptavishesh143/React-N...

If you need help let me know!

Thank You