Search code examples
react-nativescrollviewtextinput

ScrollView removing TextInput keyboard in React Native


I am using TextInput with custom clear icon to clear text. As I need to keep multiple TextInputs in screen, I used a ScrollView:

import React, {Component} from 'react';
    import {
      View,
      Text,
      ScrollView,
      StyleSheet,
      Image,
      TouchableOpacity,
      TextInput,
    } from 'react-native';

    export default class SuccessScreen extends Component {
      constructor(props) {
        super(props);
        this.state = {};
      }

      handleRightClick() {
        console.log('handleRightClick');
      }

      render() {
        return (
          <ScrollView>
            <View style={styles.SectionStyle}>
              <TextInput style={styles.input} />

              <TouchableOpacity
                style={styles.ImageStyle}
                onPress={this.handleRightClick}>
                <Image source={require('../../images/cross_icon.png')} />
              </TouchableOpacity>
            </View>
          </ScrollView>
        );
      }
    }

    const styles = StyleSheet.create({
      
      input: {
        flex: 1,
        borderColor: '#000000',
        borderBottomWidth: 1,
        height: 40,
        fontSize: 15,
        color: '#000000',
      },
      

      SectionStyle: {
        flexDirection: 'row',
        minWidth: '100%',
        height: 40,
      },

      ImageStyle: {
        height: 25,
        width: 25,
        marginLeft: -25,
        alignContent: 'center',
        resizeMode: 'stretch',
        alignItems: 'center',
      },
    });

Without the ScrollView, handleRightClick is called, but when I use the ScrollView, it just dismiss keyboard and don't call handleRightClick.


Solution

  • The ScrollView has a prop keyboardShouldPersistTaps. You should set it to 'handled' so your TouchableOpacity will handle the press instead of the ScrollView.

    <ScrollView keyboardShouldPersistTaps='handled'>
      // ...
    </ScrollView>