Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Make View "Hug" the Top of the Keyboard

Let's say I have a view that is positioned absolute at the bottom of the screen. This view contains a text input. When the text input is focused, I want the bottom of the view to touch the top of the keyboard.

I've been messing around with KeyboardAvoidingView, but the keyboard keeps going over my view. Is it not possible to make this work with position absolute?

What other method can I try? Thanks!

like image 342
Zach Avatar asked Mar 09 '17 07:03

Zach


People also ask

How do you push a view up when a keyboard appears react native?

Use android:windowSoftInputMode="adjustResize". KeyboardAvoidingView and other keyboard-related components don't work quite well if you have "adjustPan" set for your android:windowSoftInputMode in AndroidManifest. xml . Instead, you should use "adjustResize" and have a wonderful life.

How do you make your react native app respond gracefully when the keyboard pops up?

The first thing you have to do is replace the container View with the KeyboardAvoidingView and then add a behavior prop to it. If you look at the documentation you'll see that it accepts 3 different values — height, padding, position. I've found that padding works in the most predictable manner.

How do you close keyboard on button click in react native?

You can dismiss the keyboard by using Keyboard. dismiss .


1 Answers

Few days ago I have the same problem (although I have a complex view with TextInput as a child) and wanted not only the TextInput to be focused but the whole view to be "attached" to the keyboard. What's finally is working for me is the following code:

constructor(props) {
    super(props);
    this.paddingInput = new Animated.Value(0);
}

componentWillMount() {
    this.keyboardWillShowSub = Keyboard.addListener('keyboardWillShow', this.keyboardWillShow);
    this.keyboardWillHideSub = Keyboard.addListener('keyboardWillHide', this.keyboardWillHide);
}

componentWillUnmount() {
    this.keyboardWillShowSub.remove();
    this.keyboardWillHideSub.remove();
}

keyboardWillShow = (event) => {
    Animated.timing(this.paddingInput, {
        duration: event.duration,
        toValue: 60,
    }).start();
};

keyboardWillHide = (event) => {
    Animated.timing(this.paddingInput, {
        duration: event.duration,
        toValue: 0,
    }).start();
};

render() {
        return (
            <KeyboardAvoidingView behavior='padding' style={{ flex: 1 }}>
                [...]
                <Animated.View style={{ marginBottom: this.paddingInput }}>
                    <TextTranslateInput />
                </Animated.View>
            </KeyboardAvoidingView>
        );
    }

where [..] you have other views.

like image 98
vaklinzi Avatar answered Sep 20 '22 20:09

vaklinzi