Search code examples
iosreact-nativekeyboardexpo

Keyboard not being dismissed with Keyboard.dismiss in React Native


I'm looking to dismiss the keyboard when the user clicks on anywhere outside the keyboard or the input, but the keyboard is not being dismissed when I click elsewhere:

        <TouchableWithoutFeedback style={styles.container} onPress={Keyboard.dismiss}>
            <View style={styles.inputContainer}>
                <TextInput
                    placeholder="Search Term"
                    style={styles.input}
                    onChangeText={setSearch}
                    value={search}
                    returnKeyType="search"
                    onSubmitEditing={handleSubmit}
                />
            </View>
        </ TouchableWithoutFeedback>

The styling is pretty standard:

   container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    inputContainer: {
        position: 'absolute',
        top: stackHeaderHeight + 10,
        height: height * .1,
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },

Solution

  • You need to change your onPress code of TouchableWithoutFeedback

    <TouchableWithoutFeedback style={styles.container} onPress={()=> Keyboard.dismiss()}>
    
            </ TouchableWithoutFeedback>
    

    Sample working code.

    render() {
    return (
      <TouchableWithoutFeedback onPress={()=>Keyboard.dismiss()} >
        <View style={{ flex: 1 }}>
          <TextInput returnKeyType="search" style={{borderWidth:1,borderColor:'grey',marginTop:100,height:50,marginHorizontal:50}}/>
        </View>
      </TouchableWithoutFeedback>
    );
    }
    

    I think you have a problem with your style properties. Please check on your container and inputcontainer style properties. If you have any ScrollView in your render method add following

    <ScrollView keyboardShouldPersistTaps='always'>