How to set the textinput box above the Keyboard while entering the input field in react native

sejn picture sejn · Feb 6, 2019 · Viewed 21.9k times · Source

I am using react-native TextInput component. Here I need to show the InputBox above the keyboard if the user clicks on the textInput field.

I have tried below but i am facing the issues

1. Keyboard avoiding view

 a. Here it shows some empty space below the input box 
 b. Manually I need to scroll up the screen to see the input field which I was given in the text field
 c. Input box section is hiding while placing the mouse inside the input box 

2. react-native-Keyboard-aware-scroll-view

a.It shows some empty space below the input box
b.ScrollView is reset to the top of the page after I moving to the next input box

Here I set the Keyboard-aware-scroll-view inside the ScrollView component

Kindly clarify

My example code is

<SafeAreaView>
<KeyboardAvoidingView>
<ScrollView>        
        <Text>Name</Text>
            <AutoTags
            //required
             suggestions={this.state.suggestedName}
             handleAddition={this.handleAddition}
             handleDelete={this.handleDelete}
             multiline={true}
             placeholder="TYPE IN"
             blurOnSubmit={true}
             style= {styles.style}
             />
</ScrollView>   
</KeyboardAvoidingView>
</SafeAreaView>

[https://github.com/APSL/react-native-keyboard-aware-scroll-view]

Answer

basbase picture basbase · Mar 2, 2019

Give your TextInput a position: absolute styling and change its position using the height returned by the keyboardDidShow and keyboardDidHide events.

Here is a modification of the Keyboard example from the React Native documentation for demonstration:

import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';

class Example extends Component {
    state = {
        keyboardOffset: 0,
    };

    componentDidMount() {
        this.keyboardDidShowListener = Keyboard.addListener(
            'keyboardDidShow',
            this._keyboardDidShow,
        );
        this.keyboardDidHideListener = Keyboard.addListener(
            'keyboardDidHide',
            this._keyboardDidHide,
        );
    }

    componentWillUnmount() {
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove();
    }

    _keyboardDidShow(event) {
        this.setState({
            keyboardOffset: event.endCoordinates.height,
        })
    }

    _keyboardDidHide() {
        this.setState({
            keyboardOffset: 0,
        })
    }

    render() {
        return <View style={{flex: 1}}>
            <TextInput
                style={{
                    position: 'absolute',
                    width:    '100%',
                    bottom:   this.state.keyboardOffset,
                }}
                onSubmitEditing={Keyboard.dismiss}
            />
        </View>;
    }
}