Best order for KeyboardAvoidingView, SafeAreaView and ScrollView

Khaled Boussoffara picture Khaled Boussoffara · Sep 26, 2019 · Viewed 7.2k times · Source

I use react native to create a mobile app. I handle keyboard position in my screens by using KeyboardAvoidingView, SafeAreaView and ScrollView. I use this order to manage Keyboard position :

<KeyboardAvoidingView style={{ flex: 1 }} behavior="padding" enabled>
        <SafeAreaView>
          <ScrollView>
            <Header
              leftComponent={{
                icon: "cancel",
                color: "#fff",
                size: 30,
                onPress: () => navigate("Dashboard")
              }}
              centerComponent={{ text: "Ajouter une demande", style: { color: "#fff", fontSize: 18 } }}
              rightComponent={{
                icon: "help",
                color: "#fff",
                size: 30,
                fontWeight: "bold",
                onPress: () => Alert.alert("En cours de développement")
              }}
              backgroundColor="rgba(82, 159, 197, 1)"
              // outerContainerStyles={{ height: Platform.OS === "ios" ? 70 : 70 - 24 }}
              containerStyle={
                {
                  // marginTop: Platform.OS === "ios" ? 0 : 15
                }
              }
            />
            <View>
              <Input placeholder="INPUT WITH CUSTOM ICON" leftIcon={<Icon name="user" size={24} color="black" />} />
            </View>
          </ScrollView>
        </SafeAreaView>
      </KeyboardAvoidingView>

My question is : what's the best order to use those 3 components to avoid a best keyboard position

Answer

hong developer picture hong developer · Sep 26, 2019

SafeAreaView only works with iOS. Therefore, it is assumed that you use the iOS. If your project is iOS, you can use KeyboardAwareScrollView.

SafeAreaView should be at the top because it covers the area of the screen.

KeyboardAwareScrollView Example

gifimage

Usage

import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
...
<SafeAreaView>
<KeyboardAwareScrollView>
  <View>
    <TextInput />
  </View>
</KeyboardAwareScrollView>
</SafeAreaView>