Search code examples
reactjsviewkeyboardnative

How to get KeyboardAvoidingView working nicely with multiple inputs


Hi I have a problem with KeyboardAvoidingView when using multiple inputs:

import React from 'react';
import {
    View,
    KeyboardAvoidingView,
    TextInput,
    StyleSheet,
    Text,
    Platform,
    TouchableWithoutFeedback,
    Button,
    Keyboard
} from 'react-native';

const KeyboardAvoidingComponent = () => {
    return (
        <KeyboardAvoidingView
            behavior={Platform.OS === "ios" ? "padding" : "height"}
            style={styles.container}
        >
            <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
                <View style={styles.inner}>
                    <Text style={styles.header}>Header</Text>
                    <TextInput placeholder="Username" style={styles.textInput}/>
                    <TextInput placeholder="Username" style={styles.textInput}/>
                    <TextInput placeholder="Username" style={styles.textInput}/>
                    <TextInput placeholder="Username" style={styles.textInput}/>
                    <TextInput placeholder="Username" style={styles.textInput}/>
                    <TextInput placeholder="Username" style={styles.textInput}/>
                    <TextInput placeholder="Username" style={styles.textInput}/>
                    <View style={styles.btnContainer}>
                        <Button title="Submit" onPress={() => null}/>
                    </View>
                </View>
            </TouchableWithoutFeedback>
        </KeyboardAvoidingView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    inner: {
        padding: 24,
        flex: 1,
        justifyContent: "space-around"
    },
    header: {
        fontSize: 36,
        marginBottom: 48
    },
    textInput: {
        height: 40,
        borderColor: "#000000",
        borderBottomWidth: 1,
        marginBottom: 36
    },
    btnContainer: {
        backgroundColor: "white",
        marginTop: 12
    }
});

export default KeyboardAvoidingComponent;

The layout is correct before I choose a box to type in:

Inputs before clicking on a type field

But when I click on one input, the whole inputs set just crashes down, squeezing each box all in one with impossibility to read exactly where I am typing:

After choosing a field

If you have any idea of how I could just get this right. thank you.


Solution

  • I recommend you use keyboard-aware-scroll-view, just run npm i react-native-keyboard-aware-scroll-view

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

    Here is more information and uses https://github.com/APSL/react-native-keyboard-aware-scroll-view