685

If I tap onto a textinput, I want to be able to tap somewhere else in order to dismiss the keyboard again (not the return key though). I haven't found the slightest piece of information concerning this in all the tutorials and blog posts that I read.

This basic example is still not working for me with react-native 0.4.2 in the Simulator. Couldn't try it on my iPhone yet.

<View style={styles.container}>
  <Text style={styles.welcome}>
    Welcome to React Native!
  </Text>
  <Text style={styles.instructions}>
    To get started, edit index.ios.js
  </Text>
  <Text style={styles.instructions}>
    Press Cmd+R to reload,{'\n'}
    Cmd+D or shake for dev menu
  </Text>
  <TextInput
    style={{height: 40, borderColor: 'gray', borderWidth: 1}}
    onEndEditing={this.clearFocus}
  />
</View>
Osama Rizwan
  • 615
  • 1
  • 7
  • 19
TurboFish
  • 7,789
  • 4
  • 18
  • 27

38 Answers38

867

The problem with keyboard not dismissing gets more severe if you have keyboardType='numeric', as there is no way to dismiss it.

Replacing View with ScrollView is not a correct solution, as if you have multiple textInputs or buttons, tapping on them while the keyboard is up will only dismiss the keyboard.

Correct way is to encapsulate View with TouchableWithoutFeedback and calling Keyboard.dismiss()

EDIT: You can now use ScrollView with keyboardShouldPersistTaps='handled' to only dismiss the keyboard when the tap is not handled by the children (ie. tapping on other textInputs or buttons)

If you have

<View style={{flex: 1}}>
    <TextInput keyboardType='numeric'/>
</View>

Change it to

<ScrollView contentContainerStyle={{flexGrow: 1}}
  keyboardShouldPersistTaps='handled'
>
  <TextInput keyboardType='numeric'/>
</ScrollView>

or

import {Keyboard} from 'react-native'

<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
    <View style={{flex: 1}}>
        <TextInput keyboardType='numeric'/>
    </View>
</TouchableWithoutFeedback>

EDIT: You can also create a Higher Order Component to dismiss the keyboard.

import React from 'react';
import { TouchableWithoutFeedback, Keyboard, View } from 'react-native';

const DismissKeyboardHOC = (Comp) => {
  return ({ children, ...props }) => (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
      <Comp {...props}>
        {children}
      </Comp>
    </TouchableWithoutFeedback>
  );
};
const DismissKeyboardView = DismissKeyboardHOC(View)

Simply use it like this

...
render() {
    <DismissKeyboardView>
        <TextInput keyboardType='numeric'/>
    </DismissKeyboardView>
}

NOTE: the accessible={false} is required to make the input form continue to be accessible through VoiceOver. Visually impaired people will thank you!

Eric Kim
  • 10,617
  • 4
  • 29
  • 31
  • 38
    This is great, the only comment I have is that you could have used the official Keyboard api in RN, and called Keyboard.dismiss() instead of calling some RN internal utility dismissKeyboard(). But both work fine currently. – Pavle Lekic Dec 09 '16 at 09:04
  • 1
    @PavleLekic Sorry for the delay, I updated the answer along with the HOC method – Eric Kim Mar 23 '17 at 00:37
  • 3
    This works great. I had to change the syntax a little for the definition of the arrow function, to remove an unexpected token error in RN: `const DismissKeyboardHOC = (Comp) => {` – jwinn Sep 26 '17 at 20:47
  • 3
    I can't get `onPress` for `TouchableWithoutFeedback` to fire no matter what I try – Bradley Nov 01 '17 at 20:30
  • Turns out my `TouchableWithoutFeedback` component was just wrapping my input, and therefore wasn't triggering because I couldn't actually click on it (Clicking on `TextInput` overrides `TouchableWithoutFeedback`'s `onPress' - makes sense). Had to zoom out and wrap the parent component. – Bradley Nov 01 '17 at 21:31
  • I used this solution, but then i discovered Accessibility problems. Voice will not work inside the TouchableWithoutFeedback element. Anyone with the same problem found a solution? EDIT: the solution was to simply set "accessible={false}" on the element! – marco.marinangeli Dec 02 '17 at 11:18
  • test It seems to work with Text but when I have a TextInput, the tap is not caught by the TouchableWithoutFeedback's onPress. Any idea how to make it work? – Jun Jan 21 '18 at 02:42
  • My mistake. The onPress event was captured by other buttons in the parent container. But, it does work if there is no other component within the parent component to capture the touch event. – Jun Jan 21 '18 at 03:16
  • This is the solution i used and I thought it had worked. One of my views contains a ListView though and unfortunately it seems that swipes dont make it through the TouchableWithoutFeedback element. Has anyone else encountered this? Thanks – James Trickey Feb 21 '18 at 01:58
  • This solution will also work for text input inside `List`. – Harikrishnan Feb 28 '18 at 08:44
  • 2
    This solution works, but please keep in mind that you can not use swipe gestures in children of a Touchable component. – Hobbyist Apr 15 '18 at 14:34
  • If you really just wanted a View and none of the ScrollView behaviour, it helps to add bounces={false} as a property to the ScrollView. Otherwise you get the elastic overscroll on iOS. – Anthony De Smet Feb 10 '19 at 20:46
  • [Keyboard can not dismiss after use Alert](https://github.com/facebook/react-native/issues/17356) ! TextInput has `bluronSubmit={false}`. Make the field focused and show some alert. After press ok on Alert, when i try to dismiss the keyboard tapping outside the TextInput is not working! – Johncy May 27 '19 at 14:12
  • I won't downvote this but please remove it or change it as its incorrect and misleading. See 'onStartShouldSetResponder on a parent View' answers as the correct behavior with less effort. – King Friday Jul 28 '19 at 18:28
  • 2
    Why create an HoC and just add this in the root of your app tree / – Dimitri Kopriwa Apr 26 '20 at 15:52
  • `keyboardShouldPersistTaps='handled`' is the magic. – hakki Dec 16 '20 at 21:37
  • Ok my mistake was because i called `Keyboard.dimiss` instead of `Keyboard.dismiss()` – Jarrett Jan 21 '21 at 11:47
  • This is stellar - for web react I've done this and was going to try this approach https://stackoverflow.com/questions/56804790/closing-popup-on-clicking-outside-component . with a little fiddling for RN porting i feel like it might work for proof of concept, but until then this HOC worked great! thanks – Julian Mar 31 '21 at 23:09
  • Hey everyone, could anyone help me? breaks my input in the web version, I can't write inside the input anything. Are any ideads to fix it? – glushkina1 Nov 28 '21 at 02:27
  • not working, if user move from previous screen which open keypad for text input, with react-navigation v6 – Somnath Kadam Dec 06 '21 at 17:42
397

This just got updated and documented! No more hidden tricks.

import { Keyboard } from 'react-native'

// Hide that keyboard!
Keyboard.dismiss()

Github link

Osama Rizwan
  • 615
  • 1
  • 7
  • 19
Gant Laborde
  • 6,484
  • 1
  • 21
  • 30
114

Use React Native's Keyboard.dismiss()

Updated Answer

React Native exposed the static dismiss() method on the Keyboard, so the updated method is:

import { Keyboard } from 'react-native'; 

Keyboard.dismiss()

Original Answer

Use React Native's dismissKeyboard Library.

I had a very similar problem and felt like I was the only one that didn't get it.

ScrollViews

If you have a ScrollView, or anything that inherits from it like a ListView, you can add a prop that will automatically dismiss the keyboard based on press or dragging events.

The prop is keyboardDismissMode and can have a value of none, interactive or on-drag. You can read more on that here.

Regular Views

If you have something other than a ScrollView and you'd like any presses to dismiss the keyboard, you can use a simple TouchableWithoutFeedback and have the onPress use React Native's utility library dismissKeyboard to dismiss the keyboard for you.

In your example, you could do something like this:

var DismissKeyboard = require('dismissKeyboard'); // Require React Native's utility library.

// Wrap your view with a TouchableWithoutFeedback component like so.

<View style={styles.container}>

  <TouchableWithoutFeedback onPress={ () => { DismissKeyboard() } }>

    <View>

      <Text style={styles.welcome}>
        Welcome to React Native!
      </Text>

      <Text style={styles.instructions}>
        To get started, edit index.ios.js
      </Text>

      <Text style={styles.instructions}>
        Press Cmd+R to reload,{'\n'}
        Cmd+D or shake for dev menu
      </Text>

      <TextInput style={{height: 40, borderColor: 'gray', borderWidth: 1}} />

    </View>

  </TouchableWithoutFeedback>

</View>

Note: TouchableWithoutFeedback can only have a single child so you need to wrap everything below it in a single View as shown above.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
  • 5
    React Native exposed the static `dismiss()` method on the Keyboard, so the updated method is: `import { Keyboard } from 'react-native'; Keyboard.dismiss()`. – Joshua Pinter Feb 21 '17 at 19:25
  • 1
    i have a keyboard that is hanging around since i did a reload while focused on an input field. in this case `Keyboard.dismiss()` does nothing since its implementation is dependent on being focused on an input, which I no longer am. – pstanton Jun 16 '18 at 00:36
  • @pstanton What did you have to do to dismiss the keyboard, then? – Joshua Pinter Jun 17 '18 at 00:44
  • There was no way I could find, so I force closed! – pstanton Jun 17 '18 at 22:52
  • What to do if I want to restrict keyboard (don't want to close ) keyboard – Anuj Aug 20 '20 at 08:20
104

use this for custom dismissal

var dismissKeyboard = require('dismissKeyboard');

var TestView = React.createClass({
    render: function(){
        return (
            <TouchableWithoutFeedback 
                onPress={dismissKeyboard}>
                <View />
            </TouchableWithoutFeedback>
        )
    }
})
David Schumann
  • 13,380
  • 9
  • 75
  • 96
syarul
  • 2,161
  • 2
  • 20
  • 22
  • It's not documented, but the samples in react-native github repo does use it few times. – syarul Apr 30 '16 at 04:15
  • 8
    Interesting, for those curious where this comes from, it's a Utility library in React Native. Here's the source: https://github.com/facebook/react-native/blob/master/Libraries/Utilities/dismissKeyboard.js – Joshua Pinter Apr 30 '16 at 18:16
  • 1
    For some reason it didn't work, when I tried with `react-native-search-bar` – Peter G. Jul 13 '16 at 09:36
  • This is the exact equivalent of Keyboard.dismiss, which is preferable since is documented. https://github.com/facebook/react-native/blob/1490ab12ef156bf3201882eeabfcac18a1210352/Libraries/Components/Keyboard/Keyboard.js#L151 – Ricardo Stuven Apr 20 '18 at 20:33
47

The simple answer is to use a ScrollView instead of View and set the scrollable property to false (might need to adjust some styling though).

This way, the keyboard gets dismissed the moment I tap somewhere else. This might be an issue with react-native, but tap events only seem to be handled with ScrollViews which leads to the described behaviour.

Edit: Thanks to jllodra. Please note that if you tap directly into another Textinput and then outside, the keyboard still won't hide.

TurboFish
  • 7,789
  • 4
  • 18
  • 27
  • 1
    It works with scrollview but still there are some cases i'm experiencing where I can click button to change the view using navigator and keyboard still sticks at the bottom and have to manually click return key to close it :( – Piyush Chauhan Jun 10 '15 at 07:45
  • 1
    Keyboard hides when you tap outside the TextInput, but if (instead of tapping outside) you tap into another TextInput, and finally tap outside, the keyboard does not hide. Tested on 0.6.0. – jllodra Jun 17 '15 at 19:28
  • I'm seeing different behavior now. Tapping outside the TextInput hides the keyboard, even if I tap directly onto another TextInput--which is a problem because you have to tap twice on another TextInput to be able to type into it! Sigh. (with RN 0.19) – Lane Rettig Feb 04 '16 at 22:22
  • 1
    You can set scrollable to true and use keyboardShouldPersistTaps={'handled'} and keyboardDismissMode={'on-drag'} to achieve the same effect – Eric Wiener Aug 16 '18 at 22:06
  • only scrollview worked for me I don't know why,the accepted answer when i input a number keyboard dismisses – Yvon Huynh Apr 15 '20 at 07:02
39

You can import keyboard from react-native like below:

import { Keyboard } from 'react-native';

and in your code could be something like this:

render() {
    return (
      <TextInput
        onSubmit={Keyboard.dismiss}
      />
    );
  }

static dismiss()

Dismisses the active keyboard and removes focus.

Alireza
  • 100,211
  • 27
  • 269
  • 172
  • I did not need `static dismiss()`. I just added `Keyboard.dismiss()` to my onSubmit method (where `onSubmitEditing={() => {this.onSubmit()}})` – SherylHohman Apr 30 '18 at 07:49
38

I'm brand new to React, and ran into the exact same issue while making a demo app. If you use the onStartShouldSetResponder prop (described here), you can grab touches on a plain old React.View. Curious to hear more experienced React-ers' thoughts on this strategy / if there's a better one, but this is what worked for me:

containerTouched(event) {
  this.refs.textInput.blur();
  return false;
}

render() {
  <View onStartShouldSetResponder={this.containerTouched.bind(this)}>
    <TextInput ref='textInput' />
  </View>
}

2 things to note here. First, as discussed here, there's not yet a way to end editing of all subviews, so we have to refer to the TextInput directly to blur it. Second, the onStartShouldSetResponder is intercepted by other touchable controls on top of it. So clicking on a TouchableHighlight etc (including another TextInput) within the container view will not trigger the event. However, clicking on an Image within the container view will still dismiss the keyboard.

David Schumann
  • 13,380
  • 9
  • 75
  • 96
hunteros
  • 1,137
  • 11
  • 20
  • It definitely works. But as you said, Im curious as well if this is the right way. Hope they solve it soon (https://github.com/facebook/react-native/issues/113 ) – mutp Aug 22 '15 at 09:35
  • Great this worked for me. My scroll view was not working with the touchable methods! Thanks! – James Trickey Feb 21 '18 at 02:10
34

Use ScrollView instead of View and set the keyboardShouldPersistTaps attribute to false.

<ScrollView style={styles.container} keyboardShouldPersistTaps={false}>
    <TextInput
        placeholder="Post Title"
        onChange={(event) => this.updateTitle(event.nativeEvent.text)}
        style={styles.default}/>
 </ScrollView>
David Schumann
  • 13,380
  • 9
  • 75
  • 96
Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77
  • According to the documentation, the `keyboardShouldPersistTaps` attribute defaults to false when using a `ScrollView`. I just updated my react-native to the latest version and the problem with switching to a second `TextInput` still persists. The keyboard then is not dismissible. Have you found a solution for this specific problem? – TurboFish Jul 20 '15 at 12:46
  • 1
    The docs were incorrect, but have now been updated, see this PR: https://github.com/facebook/react-native/issues/2150 – Ryan McDermott Oct 09 '15 at 16:24
  • What does `keyboardShouldPersistTaps` do? Why is it relevant here? Thanks – Lane Rettig Feb 04 '16 at 22:24
  • 1
    Warning: 'keyboardShouldPersistTaps={false}' is deprecated. Use 'keyboardShouldPersistTaps="never"' instead – Milan Rakos Apr 04 '18 at 08:05
24

Wrapping your components in a TouchableWithoutFeedback can cause some weird scroll behavior and other issues. I prefer to wrap my topmost app in a View with the onStartShouldSetResponder property filled in. This will allow me to handle all unhandled touches and then dismiss the keyboard. Importantly, since the handler function returns false the touch event is propagated up like normal.

 handleUnhandledTouches(){
   Keyboard.dismiss
   return false;
 }

 render(){
    <View style={{ flex: 1 }} onStartShouldSetResponder={this.handleUnhandledTouches}>
       <MyApp>
    </View>
  }
Karthikeyan
  • 196
  • 2
  • 10
Scottmas
  • 1,082
  • 10
  • 22
  • 1
    Thanks for your answer @Scottmas. I ended up using it instead of TouchableWithoutFeedback, because of your "weird scroll behavior and other issues" comment. But if I wasn't blindly trusting your words, can you elaborate on your comment? :) – kuhr Mar 17 '20 at 10:53
  • https://sourcefreeze.com/hide-keyboard-in-react-native/ – Bharathi Devarasu Dec 22 '22 at 07:09
21

The simplest way to do this

import {Keyboard} from 'react-native'

and then use the function Keyboard.dismiss()

That's all.

Here is a screenshot of my code so you can understand faster.

Import Keyboard from react native. Also import TouchableWithoutFeedback

Now wrap the entire view with TouchableWithoutFeedback and onPress function is keyboard.dismiss()

Here is the example TouchableWithoutFeedback and Keyboard.dismiss()

In this way if user tap on anywhere of the screen excluding textInput field, keyboard will be dismissed.

TripleM
  • 1,096
  • 7
  • 20
19

There are a few ways, if you control of event like onPress you can use:

import { Keyboard } from 'react-native'

onClickFunction = () => {
     Keyboard.dismiss()
}

if you want to close the keyboard when the use scrolling:

<ScrollView keyboardDismissMode={'on-drag'}>
     //content
</ScrollView>

More option is when the user clicks outside the keyboard:

<KeyboardAvoidingView behavior='padding' style={{ flex: 1}}>
    //inputs and other content
</KeyboardAvoidingView>
Idan
  • 3,604
  • 1
  • 28
  • 33
  • 1
    Guys, the question is still actual but question is 4 years old(end of 2019 now). RN now is soo simple and easy to use. We have to review all abilities with help of we can achieve solution for this question. Let upvote this comment! – Link Nov 01 '19 at 10:56
18

If any one needs a working example of how to dismiss a multiline text input here ya go! Hope this helps some folks out there, the docs do not describe a way to dismiss a multiline input at all, at least there was no specific reference on how to do it. Still a noob to actually posting here on the stack, if anyone thinks this should be a reference to the actual post this snippet was written for let me know.

import React, { Component } from 'react'
import {
  Keyboard,
  TextInput,
  TouchableOpacity,
  View,
  KeyboardAvoidingView,
} from 'react-native'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      behavior: 'position',
    }
    this._keyboardDismiss = this._keyboardDismiss.bind(this)
  }

  componentWillMount() {
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
  }

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

  _keyboardDidHide() {
    Keyboard.dismiss()
  }

  render() {
    return (
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={this.state.behavior}
      >
        <TouchableOpacity onPress={this._keyboardDidHide}>
          <View>
            <TextInput
              style={{
                color: '#000000',
                paddingLeft: 15,
                paddingTop: 10,
                fontSize: 18,
              }}
              multiline={true}
              textStyle={{ fontSize: '20', fontFamily: 'Montserrat-Medium' }}
              placeholder="Share your Success..."
              value={this.state.text}
              underlineColorAndroid="transparent"
              returnKeyType={'default'}
            />
          </View>
        </TouchableOpacity>
      </KeyboardAvoidingView>
    )
  }
}
David Schumann
  • 13,380
  • 9
  • 75
  • 96
austin reynolds
  • 221
  • 2
  • 6
  • What to do if I want to restrict keyboard (don't want to close ) keyboard on an event ? – Anuj Aug 20 '20 at 08:21
16

Updated usage of ScrollView for React Native 0.39

<ScrollView scrollEnabled={false} contentContainerStyle={{flex: 1}} />

Although, there is still a problem with two TextInput boxes. eg. A username and password form would now dismiss the keyboard when switching between inputs. Would love to get some suggestions to keep keyboard alive when switching between TextInputs while using a ScrollView.

Anshuul Kai
  • 3,876
  • 2
  • 27
  • 48
  • 3
    It appears that `0.40` updates `keyboardShouldPersistTaps` from a `boolean` to an `enum` with a possible value of 'handled` which is suppose to fix this. – Anshuul Kai Jan 12 '17 at 22:32
14
const dismissKeyboard = require('dismissKeyboard');
dismissKeyboard(); //dismisses it

Approach No# 2;

Thanks to user @ricardo-stuven for pointing this out, there is another better way to dismiss the keyboard which you can see in the example in the react native docs.

Simple import Keyboard and call it's method dismiss()

Adeel Imran
  • 13,166
  • 8
  • 62
  • 77
  • 1
    This is the exact equivalent of Keyboard.dismiss, which is preferable since is documented. https://github.com/facebook/react-native/blob/1490ab12ef156bf3201882eeabfcac18a1210352/Libraries/Components/Keyboard/Keyboard.js#L151 – Ricardo Stuven Apr 20 '18 at 20:35
  • At the time I gave this answer, this was not documented. Thanks for mentioning it. I'll update my answer. – Adeel Imran Apr 21 '18 at 21:21
12

I just tested this using the latest React Native version (0.4.2), and the keyboard is dismissed when you tap elsewhere.

And FYI: you can set a callback function to be executed when you dismiss the keyboard by assigning it to the "onEndEditing" prop.

Jonathan Huang
  • 2,076
  • 17
  • 14
  • I was debugging the "onEndEditing" callback, but it never triggered before; I'm going to look into this with the newer version of react native, thanks for your suggestion – TurboFish May 12 '15 at 21:36
12

Using KeyBoard API from react-native does the trick.

import { Keyboard } from 'react-native'

// Hide the keyboard whenever you want using !
Keyboard.dismiss()
Muhammad Humza
  • 137
  • 1
  • 5
10

How about placing a touchable component around/beside the TextInput?

var INPUTREF = 'MyTextInput';

class TestKb extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <View style={{ flex: 1, flexDirection: 'column', backgroundColor: 'blue' }}>
                <View>
                    <TextInput ref={'MyTextInput'}
                        style={{
                            height: 40,
                            borderWidth: 1,
                            backgroundColor: 'grey'
                        }} ></TextInput>
                </View>
                <TouchableWithoutFeedback onPress={() => this.refs[INPUTREF].blur()}>
                    <View 
                        style={{ 
                            flex: 1, 
                            flexDirection: 'column', 
                            backgroundColor: 'green' 
                        }} 
                    />
                </TouchableWithoutFeedback>
            </View>
        )
    }
}
David Schumann
  • 13,380
  • 9
  • 75
  • 96
boredgames
  • 11,254
  • 5
  • 25
  • 17
10

If i'm not mistaken the latest version of React Native has solved this issue of being able to dismiss the keyboard by tapping out.

10

Wrap your whole component with:

import { TouchableWithoutFeedback, Keyboard } from 'react-native'

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

Worked for me

Arthur Mastropietro
  • 673
  • 1
  • 7
  • 22
9

We can use keyboard and tochablewithoutfeedback from react-native

const DismissKeyboard = ({ children }) => (
  <TouchableWithoutFeedback
    onPress={() => Keyboard.dismiss()}
  >
    {children}
  </TouchableWithoutFeedback>
);

And use it in this way:

const App = () => (
  <DismissKeyboard>
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="username"
        keyboardType="numeric"
      />
      <TextInput
        style={styles.input}
        placeholder="password"
      />
    </View>
  </DismissKeyboard>
);

I also explained here with source code.

Mash
  • 153
  • 1
  • 8
8

Keyboard module is used to control keyboard events.

  • import { Keyboard } from 'react-native'
  • Add below code in render method.

    render() { return <TextInput onSubmitEditing={Keyboard.dismiss} />; }

You can use -

Keyboard.dismiss()

static dismiss() Dismisses the active keyboard and removes focus as per react native documents.

7

https://facebook.github.io/react-native/docs/keyboard.html

Use

Keyboard.dismiss(0);

to hide the keyboard.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
6

Using keyboardShouldPersistTaps in the ScrollView you can pass in "handled", which deals with the issues that people are saying comes with using the ScrollView. This is what the documentation says about using 'handled': the keyboard will not dismiss automatically when the tap was handled by a children, (or captured by an ancestor). Here is where it's referenced.

Samuel
  • 61
  • 1
  • 2
  • This worked for me! (however I had to add it inside my 3rd party library `react-native-keyboard-aware-scroll-view`). – Nick Grealy Jan 13 '18 at 12:20
6

First import Keyboard

import { Keyboard } from 'react-native'

Then inside your TextInput you add Keyboard.dismiss to the onSubmitEditing prop. You should have something that looks like this:

render(){
  return(
    <View>
      <TextInput 
        onSubmitEditing={Keyboard.dismiss}
       />
    </View>
  )  
}
Andrew
  • 26,706
  • 9
  • 85
  • 101
Rocky
  • 457
  • 4
  • 11
6

Use Keyboard.dismiss() to dismiss keyboard at any time.

Rover
  • 661
  • 2
  • 18
  • 39
6

Wrap the View component that is the parent of the TextInput in a Pressable component and then pass Keyboard. dismiss to the onPress prop. So, if the user taps anywhere outside the TextInput field, it will trigger Keyboard. dismiss, resulting in the TextInput field losing focus and the keyboard being hidden.

<Pressable onPress={Keyboard.dismiss}>
  <View>
    <TextInput
      multiline={true}
      onChangeText={onChangeText}
      value={text}
      placeholder={...}
     />
   </View>
</Pressable>
Hossein Arsheia
  • 361
  • 1
  • 4
  • 7
Thumppi
  • 71
  • 1
  • 5
3

in ScrollView use

keyboardShouldPersistTaps="handled" 

This will do your job.

clemens
  • 16,716
  • 11
  • 50
  • 65
gamingumar
  • 979
  • 8
  • 14
  • What to do if I want to restrict keyboard (don't want to close ) keyboard on an event ? – Anuj Aug 20 '20 at 08:21
3

There are many ways you could handle this, the answers above don't include returnType as it was not included in react-native that time.

1: You can solve it by wrapping your components inside ScrollView, by default ScrollView closes the keyboard if we press somewhere. But incase you want to use ScrollView but disable this effect. you can use pointerEvent prop to scrollView pointerEvents = 'none'.

2: If you want to close the keyboard on a button press, You can just use Keyboard from react-native

import { Keyboard } from 'react-native' and inside onPress of that button, you can useKeyboard.dismiss()'.

3: You can also close the keyboard when you click the return key on the keyboard, NOTE: if your keyboard type is numeric, you won't have a return key. So, you can enable it by giving it a prop, returnKeyType to done. or you could use onSubmitEditing={Keyboard.dismiss},It gets called whenever we press the return key. And if you want to dismiss the keyboard when losing focus, you can use onBlur prop, onBlur = {Keyboard.dismiss}

Sarmad Shah
  • 3,725
  • 1
  • 20
  • 42
3

2023 answer:

You can add thereturnKeyType prop to the TextInput to specify the text displayed on the return key of the keyboard. Setting it to  "done"  will display a "Done" button, which will dismiss the keyboard when pressed.

 <TextInput
    style={{height: 40, borderColor: 'gray', borderWidth: 1}}
    onEndEditing={this.clearFocus}
    returnKeyType="done"
  />

And it'll show the "done" button like this:

enter image description here

1

Keyboard.dismiss() will do it. But sometimes it may lose the focus and Keyboard will be unable to find the ref. The most consistent way to do is put a ref=_ref to the textInput, and do _ref.blur() when you need to dismiss, and _ref.focus() when you need to bring back the keyboard.

Bruce Lin
  • 2,700
  • 6
  • 28
  • 38
1

Here is my solution for Keyboard dismissing and scrolling to tapped TextInput (I am using ScrollView with keyboardDismissMode prop):

import React from 'react';
import {
  Platform,
  KeyboardAvoidingView,
  ScrollView
} from 'react-native';

const DismissKeyboard = ({ children }) => {
  const isAndroid = Platform.OS === 'android';
  const behavior = isAndroid ? false : 'padding';

  return (
    <KeyboardAvoidingView
      enabled
      behavior={ behavior }
      style={{ flex: 1}}
    >
      <ScrollView
        keyboardShouldPersistTaps={'always'}
        keyboardDismissMode={'on-drag'}
      >
        { children }
      </ScrollView>
    </KeyboardAvoidingView>
  );
};

export default DismissKeyboard;

usage:

render(){
   return(
     <DismissKeyboard>
       <TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({text})}
        value={this.state.text}
      />
     </DismissKeyboard>
   );
}

Artem Shevtsov
  • 496
  • 5
  • 13
1

use this package react-native-keyboard-aware-scroll-view

use that component as your root component

since this package react-native-keyboard-aware-scroll-view also have an scrollView you need to add this to it:

<KeyboardAwareScrollView keyboardShouldPersistTaps="handled"> <ScrollView keyboardShouldPersistTaps="handled"></ScrollView> </KeyboardAwareScrollView>

Cyrus Zei
  • 2,589
  • 1
  • 27
  • 37
1

import {Keyboard} from 'react-native';

use Keyboard.dismiss() to hide your keyboard in any onClick or onPress event.

jyotishman saikia
  • 2,079
  • 1
  • 15
  • 11
0

For hide keyboard use Keyboard.dismiss() inside TextInput.

Sid009
  • 421
  • 5
  • 16
0

The onStartShouldSetResponder prop stops the touch event propagation towards the TouchableWithoutFeedback element.

<TouchableWithoutFeedback onPress={...}>
  <View>
    <ScrollView>
      <View onStartShouldSetResponder={() => true}>
        // Scrollable content
      </View>
    </ScrollView>
  </View>
</TouchableWithoutFeedback>
Rajesh N
  • 6,198
  • 2
  • 47
  • 58
0
{/* KeyboardAvoidingView is to avoid the keyboard if the screen is smaller. it will shift the UI content up  */}
{/* keyboardVerticalOffset tells where our view starts */}
{/* behaviour "padding" best works for ios, "height" best works for android */}
<KeyboardAvoidingView
    // maybe you have a header and you want to start after header
    keyboardVerticalOffset={yourViewHeaderHeight}
    // "behavior" tells what property should change in case of changing our view
    behavior={Platform.OS === "ios" ? "padding" : "height"}
    style={{ flex: 1 }}
>
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
0
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';

use keyboardAwareScrollView as parent

Umer Arain
  • 17
  • 2
-1

Use ScrollView instead of View with the attribute of keyboardShouldPersistTaps={"always"}. It hides the keyboard when we click anywhere inside of the screen

<ScrollView keyboardShouldPersistTaps={"always"}>
 <View style={styles.container}>
  <Text style={styles.welcome}>
    Welcome to React Native!
  </Text>
  <Text style={styles.instructions}>
    To get started, edit index.ios.js
  </Text>
  <Text style={styles.instructions}>
    Press Cmd+R to reload,{'\n'}
    Cmd+D or shake for dev menu
  </Text>
  <TextInput
    style={{height: 40, borderColor: 'gray', borderWidth: 1}}
    onEndEditing={this.clearFocus}
  />
 </View>
</ScrollView>
Karthikeyan Ganesan
  • 1,901
  • 20
  • 23