Dismiss keyboard in multiline TextInput in React native - react-native

When the user presses the Return key in a multiline TextInput, a new line is created and the keyboard continues to be visible. How should the keyboard be dismissed for multiline TextInput in React native?
I did some research. I found that clicking on the View outside the TextInput does not blur the TextInput, which is causing the keyboard to remain visible.
<View style={styles.container}>
<TextInput
placeholder="To"
style={styles.input}
value={this.state.to}
onChangeText={(to) => this.setState({to})}
/>
<TextInput
placeholder="Text"
style={styles.textarea}
multiline={true}
numberOfLines={4}
value={this.state.text}
onChangeText={(text) => this.setState({text})}
/>
</View>
For ScrollView, there is a prop - keyboardShouldPersistTaps which causes the TextInput to blur. Is there any equivalent of that for View? I want the multiline TextInput to blur so that the keyboard gets dismissed.

TextInput has a blurOnSubmit prop; when set to true, the return key dismisses the keyboard.
However currently the prop does not work on Android. I've posted an issue on the subject:
https://github.com/facebook/react-native/issues/8778

Hope it helps other , as wasted time on reading many github threads and issues..
By doing below code , you keyboard show return key you wanted for example "done", "go" and also dismiss the keyboard when you press return key in my case done key while using multi line seamlessly.
import {Textinput, ScrollView, Keyboard} from 'react-native';
// ...code
<TextInput
keyboardType="default"
returnKeyType="done"
multiline={true}
blurOnSubmit={true}
onSubmitEditing={()=>{Keyboard.dismiss()}}
/>

This is a simplified version of austin's very helpful answer above.
If you convert the View you have for your screen/component into a TouchableOpacity with activeOpacity={1} (this prevents any fading or opacity effects), you can then pass it:
onPress={() => Keyboard.dismiss()}
Make sure you've imported TouchableOpacity and Keyboard from 'react-native' and you're good.

Banged my head against this for a few hours and after fiddling around and some dumb luck finally figured out how to make a multiline TextInput dismiss by just touching outside the text box. Little Example for ya'll hope that someone else finds this useful because the docs do not make it all apparent that you can get multilines to dismiss easily...
import React, { Component} from 'react'`
import {
keyboardAvoidingView,
Keyboard,
StatusBar,
StyleSheet,
TextInput,
View,
} 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: '#000',
paddingLeft: 15,
paddingTop: 10,
fontSize: 18,t}
multiline={true}
textStyle={{ fontSize: '20', fontFamily: 'Montserrat-Medium' }}
placeholder="Share your Success..."
value={this.state.text}
underlineColorAndroid="transparent"
returnKeyType={'default'}
/>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
);
}
}

To complete my comment about returnKeyType, you also need to set blurOnSubmit={true} which will trigger onSubmitEditing event handler too when Done is pressed.
See example https://rnplay.org/apps/0HIrmw for details.

as long as there is only one done button, we still need to decide what this return/done button does. In this case I will propose adding another dismiss button to the keyboard by using InputAccessoryView. Following code is copied from https://dev.to/vladimirvovk/react-native-ios-keyboard-with-a-custom-button-15h0
<TextInput
...
inputAccessoryViewID="Next"
/>
<TextInput
...
ref={nextFieldRef}
inputAccessoryViewID="Done"
/>
<InputAccessoryView nativeID="Next">
<View style={styles.accessory}>
<Button
onPress={() => nextFieldRef.current.focus()}
title="Next"
/>
</View>
</InputAccessoryView>

If anyone is still having trouble with this, specifically around keeping the return key for adding new lines and dismissing the keyboard when clicking outside of the input, the regular view component does not blur the TextField when you click outside of the component. However if you use a ScrollView instead of a regular View it will trigger the onBlur effect when you click anywhere on the screen and the below code will dismiss the keyboard and keep the return key for adding new lines. You can set scrollEnabled={false} on the scroll view if you don't want scrolling and it will still trigger the events
<TextField
value={value}
placeholder="Description..."
multiline
numberOfLines={20}
keyboardType="default"
onBlur={() => {
Keyboard.dismiss();
}}
/>

Keyboard.dismiss() solved the issue for me.
<TextInput
keyboardType="default"
returnKeyType="done"
multiline={true}
blurOnSubmit={true}
onSubmitEditing={()=>{Keyboard.dismiss()}}
/>

Related

react-native-elements - android - <ListItem> onPress argument not triggering.......ONLY when debugging

This is a very strange one.....when I am not debugging everything works fine.....but as soon as I turn on debugging the onPress functionality of ListItem within FlatList no longer responds to a press.
This only started happening yesterday and I havent made any code changes. Code below:
import { StyleSheet, Text, View, FlatList, ActivityIndicator, Alert } from 'react-native';
import {ListItem, Avatar} from 'react-native-elements';
<FlatList
data={this.props.data}
keyExtractor={(item, index) => {
return index.toString();
}}
return (
<View>
<ListItem
onPress={() => {
this.props.flatListItemPressHandler(item);
}}>
<ListItem.Content>
<ListItem.Title style={{fontWeight: 'bold', fontSize: 20}}>
{item.name}
</ListItem.Title>
</ListItem.Content>
<ListItem.Chevron />
</ListItem>
</View>
);
}}
ItemSeparatorComponent={this.renderSeparator}
onEndReached={this.props._handleLoadMore}
onEndReachedThreshold={0.3}
/>
Figured it out....apparently when in debug mode....the device is interpreting a regular press as a long press. I added onLongPress prop to ListItem and simply copied the function used for onPress. Bit of a hack but at least I can continue working.

Is that possible to force keyboard gone immediately in React Native? [duplicate]

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>
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!
This just got updated and documented! No more hidden tricks.
import { Keyboard } from 'react-native'
// Hide that keyboard!
Keyboard.dismiss()
Github link
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.
use this for custom dismissal
var dismissKeyboard = require('dismissKeyboard');
var TestView = React.createClass({
render: function(){
return (
<TouchableWithoutFeedback
onPress={dismissKeyboard}>
<View />
</TouchableWithoutFeedback>
)
}
})
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.
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.
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.
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>
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>
}
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.
Now wrap the entire view with TouchableWithoutFeedback and onPress function is keyboard.dismiss()
Here is the example
In this way if user tap on anywhere of the screen excluding textInput field, keyboard will be dismissed.
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>
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>
)
}
}
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.
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()
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.
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.
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>
)
}
}
Wrap your whole component with:
import { TouchableWithoutFeedback, Keyboard } from 'react-native'
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
...
</TouchableWithoutFeedback>
Worked for me
Using KeyBoard API from react-native does the trick.
import { Keyboard } from 'react-native'
// Hide the keyboard whenever you want using !
Keyboard.dismiss()
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.
https://facebook.github.io/react-native/docs/keyboard.html
Use
Keyboard.dismiss(0);
to hide the keyboard.
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.
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>
)
}
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.
Use Keyboard.dismiss() to dismiss keyboard at any time.
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>
in ScrollView use
keyboardShouldPersistTaps="handled"
This will do your job.
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}
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.
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>
);
}

How to disable keyboard in react native

I created a screen keyboard component that I want to disable the platform's keyboard, how I can disable it?
<TextInput
secureTextEntry
ref="Pin"
selectionColor="#656565"
keyboardType="numeric"
activeColor="#656565"
inactiveColor="#fff"
autoFocus={false}
ignoreCase
codeLength={4}
inputPosition="center"
size={50}
onFulfill={isValid => this}
codeInputStyle={{ borderWidth: 1.5 }}
/>
Just write showSoftInputOnFocus={false} in <TextInput> like this:
<TextInput showSoftInputOnFocus={false} />
I had issues also. No other solutions was working for me. This will display text input field and it will be clickable but not editable.
<TouchableOpacity onPress={this.openPinKeyboard}>
<View pointerEvents="none">
<Input editable={false} value="1234" />
</View>
</TouchableOpacity>
I think you need to add something like:
<TextInput showSoftInputOnFocus={false} keyboardType="numeric" />
setting keyboardType to null worked for me
EDIT:
this only worked in the simulator, running it on an actual device the native keyboard still appeared.
wrapping the <TextInput /> in a <TouchableWithoutFeedback> element in the example below worked.
<TouchableWithoutFeedback onPress={Keyboard.dismiss} >
<TextInput />
</TouchableWithoutFeedback>
You may try to set keyboardType to none, if it doesn't work another alternative is to set the editable prop to false.
Potential answers can be found here : https://github.com/facebook/react-native/issues/14045
<TextInput showSoftInputOnFocus={false}/>
This work for me, sometime I need onFocus action to navigate new screen, and don't need keyboard open animation. Prop Editable will disable textfield, can not pressable
try this solution i hope this will work for android and ios both...
// Step 1: Get Keyboard, TouchableWithoutFeedback from ‘react-native’;
import { View, TextInput, StyleSheet, Keyboard, TouchableWithoutFeedback } from 'react-native';
// Step 2: Create an arrow function to write dismiss keyboard code
const DismissKeyboard = ({ children }) => (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
{children}
</TouchableWithoutFeedback>
);
// Step 3: Wrap all TextInput inside <DismissKeyboard> </DismissKeyboard>
//Example
<DismissKeyboard>
<View style={styles.container}>
<TextInput style={styles.input} placeholder="email" />
<TextInput style={styles.input} placeholder="password" />
</View>
</DismissKeyboard>
The easiest solution is to use the onFocus prop on TextInput.
Import Keyboard from ‘react-native’
import {Keyboard, TextInput} from
'react-native'
Then pass Keyboard.dismiss() to TextInput onFocus prop, to stop the keyboard from popping up when focused.
<TextInput onFocus = {()=> Keyboard.dismiss()} .../>
Now test the input field by pressing it to see if the keyboard will pop up
just put this under text input tag this worked for me in react-native
<TextInput
//this line
editable={false}
/>
you can do it by pointerEvents="none"
<View pointerEvents="none">
<TextInput
focusable={false}
style={{color: '#00000000'}}
onChangeText={setEmail}
/>
</View>

How to tap on a submit button in the view without having to dismiss a keyboard first?

I am using react native to implement a community feed. In each post in the feed, I can comment as seen below.
However, the issue is after I enter a comment and want to press on the submit icon on the right, the keyboard will dismiss first before I can tap on the icon to submit the text.
QUESTION:
How can I immediately submit my text after pressing the submit icon without tapping twice (once to dismiss the keyboard, and second to submit)
Here's a snippet of my implementation:
//Code for comments section/box
<View style={styles.commentSectionContainer}>
<View style={[textInputStyle.dark, textInputStyle.compact]}>
<LocalizedTextInput
multiline={false}
autoCorrect={true}
onChangeText={onCommentTextChange}
placeholder="placeholder/writeComment"
style={[textInputStyle.default, {fontSize: 13}]}
underlineColorAndroid="transparent"
value={textComment}
onSubmitEditing={() => {
if (textComment) {
onSubmitComment();
}
}}
returnKeyType="send"
/>
<View style={styles.iconSubmitContainer}>
<IconButton style={styles.commentSubmit} iconName="send" isDisabled={textComment === ''} onPress={onSubmitComment} hitSlop={hitSlop} />
</View>
</View>
</View>
Localized Text Input is using the following textinput
<View style={{flex: 1}}>
<TextInput
multiline={multiline}
style={[defaultStyle, {flex: 1}]}
underlineColorAndroid="transparent"
autoCorrect={true}
{...otherProps}
/>
</View>
The posts are all wrapped in a scrollView.
I tried to use "keyboardShouldPersistTaps" and keyboardDismissMode="Drag-on" but it doesn't produce the expected experience.. The user should be able to dismiss the keyboard by tapping anywhere outside the textinput box instead of requiring to scroll.
If your parent is a ScrollView component, then passing the prop keyboardShouldPersistTaps="always" should do the trick. See the official documentation here.
As Ankit suggested the prop needs to be passed to the scroll view but if that isn't giving you the desired results TextInput has a blur() method that you can call using a ref of that TextInput. Maybe that would help.

TextInput sometimes doesn't focus when located in a Modal

I open a Modal where there is a TextInput on top. My TextInput component has the autoFocus set to true. I can say my TextInput is focused about 6 times on 10 (open/close Modal). When it's not focused and if I try to tap (even several times) on TextInput, it doesn't want to focus.
I made another test, I set the autoFocus to false. When I open my Modal then I immediately tap the TextInput to get the focus, sometimes I have to tap twice before I get the focus on. So, it's like something didn't finish its loading before I could tap and get the focus. If I do the same test but I wait maybe 2 seconds before I do a first tap, I always get the focus.
So did you know if there is a conflict between Modal / TextInput / Keyboard?
Here is my code, in case:
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.addressButton}
onPress={() => {
this.props.feedList([]);
this.props.onPressBackButton();
}}
>
<Linearicon name="arrow-left" size={30} color="white" />
</TouchableOpacity>
<View
style={styles.searchBox}
>
<Linearicon style={styles.searchIcon} name="magnifier" size={16} color="#999999" />
<TextInput
style={[styles.searchBoxText, styles.searchBoxTextInput]}
placeholder="Recherchez une adresse..."
autoFocus={false}
placeholderTextColor='#999999'
autoCorrect={false}
onChangeText={(text) => this.onChangeText(text)}
value={this.state.address}
/>
</View>
</View>
)
I also ran into a similar kind of problem. My TextInput has autoFocus in a modal. The TextInput focus worked, but the keyboard sometimes opened and sometimes it did not open. It appears to be a race condition, where autoFocus assigns focus before the modal is visible. The solution was to use onShow attribute in Modal.
<Modal onShow={() => {this.textInput.focus();}} >
<TextInput ref={input => {this.textInput = input;}} />
</Modal>
setting the height for TextInput works.
example
<TextInput style={{textAlign:'center', fontSize:18, height:50,paddingBottom:35}} autoFocus={false} placeholder="Enter Name" placeholderTextColor="grey"/>
I also had the same issue like sometimes it was not get focus while reopen the modal. I agree with the #Saravanan's comment with just one addition by calling blur method before focus to textinput. That worked for me.
<Modal onShow={() => {
this.textInput.blur();
this.textInput.focus();
}}>
<TextInput ref={input => {this.textInput = input;}} />
</Modal>
I had the same issue, autoFocus prop seems kinda buggy when TextInput is inside modal, try this:
export default function Component() {
const inputRef = React.useRef(null);
return (
<Modal isVisible={true} onShow={() => inputRef.current.focus()} >
<TextInput ref={inputRef} />
</Modal>
}
I have the same issue. Whenever TextInput is in a Modal the autofocus is super buggy. Probably a bug. Using RN 0.27.2.