The React Native Equivalent of Tap Gesture Recognizer and resignFirstResponder

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Having trouble dismissing the keyboard in your React Native app on iOS? Would you like the keyboard to simply go away after a user taps somewhere else on the screen after entering some text into a TextInput? Here’s what you’re looking for: <TouchableWithoutFeedback> and Keyboard.dismiss() are the React Native equivalents of Tap Gesture Recognizer and resignFirstResponder. Simply wrap your view in a <TouchableWithoutFeedback> component and call the Keyboard.dismiss() method onPress and the keyboard will automatically dismiss itself when a user taps an area of the screen outside of the currently selected <TextInput>:

import React, { Component } from 'react';
import {
Alert,
Button,
StyleSheet,
Text,
TextInput,
Keyboard,
TouchableWithoutFeedback,
View
} from 'react-native';
class DismissKeyboardExample extends Component {
constructor(props) {
super(props);
this.state = {
emailTextInput: "",
passwordTextInput: ""
};
}
handleEmailTextInput(text) {
let previousState = this.state;
let newState = previousState;
newState.emailTextInput = text;
this.setState(newState);
}
handlePasswordTextInput(text) {
let previousState = this.state;
let newState = previousState;
newState.passwordTextInput = text;
this.setState(newState);
}
handleTestSignupForm() {
let email = this.state.emailTextInput;
let password = this.state.passwordTextInput;
let info = "email entered: " + email + "\n";
info += "password entered: " + password;
alert(info);
let previousState = this.state;
let newState = previousState;
newState.emailTextInput = "";
newState.passwordTextInput = "";
this.setState(newState);
}
render() {
return (
<TouchableWithoutFeedback
accessible={false}
onPress={ () => Keyboard.dismiss() }>
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Dismiss Keyboard Example</Text>
<TextInput
placeholder="Email"
onChangeText={ (text) => this.handleEmailTextInput(text) }
value={this.state.emailTextInput} />
<TextInput
placeholder="Password"
onChangeText={ (text) => this.handlePasswordTextInput(text) }
value={this.state.passwordTextInput} />
<Button
title="Sign Up"
onPress={ () => this.handleTestSignupForm() } />
</View>
</TouchableWithoutFeedback>
);
}
}
export default DismissKeyboardExample;
 

topherPedersen