Methods to Click Out Of Onfocus Text Input in React Native

In React Native, if you want to dismiss the keyboard (or effectively “click out”) when a user taps outside of a `TextInput`, you can achieve this by using a `TouchableWithoutFeedback` component or the `Keyboard.dismiss()` function.

Here’s a Step-by-Step Guide on How to Click out of Onfocus Text Input in React Native

Method 1: Using TouchableWithoutFeedback

Wrap your entire screen inside a `TouchableWithoutFeedback` and dismiss the keyboard when the user taps outside the input.

javascript

import React from ‘react’;
import { Keyboard, TextInput, TouchableWithoutFeedback, View } from ‘react-native’;

const DismissKeyboardExample = () => {
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={{ flex: 1, justifyContent: ‘center’, alignItems: ‘center’ }}>
<TextInput
style={{
height: 40,
borderColor: ‘gray’,
borderWidth: 1,
width: ‘80%’,
paddingHorizontal: 10,
}}
placeholder=”Tap outside to dismiss keyboard”
/>
</View>
</TouchableWithoutFeedback>
);
};

export default DismissKeyboardExample;

Method 2: Using Keyboard.dismiss() with Pressable (or any clickable component)

Alternatively, you can use `Keyboard.dismiss()` within any component that can handle touches. This can be useful if you want more control over which areas will dismiss the keyboard.

javascript

import React from ‘react’;
import { Keyboard, TextInput, Pressable, View } from ‘react-native’;

const DismissKeyboardExample = () => {
return (
<Pressable style={{ flex: 1 }} onPress={Keyboard.dismiss}>
<View style={{ flex: 1, justifyContent: ‘center’, alignItems: ‘center’ }}>
<TextInput
style={{
height: 40,
borderColor: ‘gray’,
borderWidth: 1,
width: ‘80%’,
paddingHorizontal: 10,
}}
placeholder=”Tap outside to dismiss keyboard”
/>
</View>
</Pressable>
);
};

export default DismissKeyboardExample;

Notes

1. TouchableWithoutFeedback and Pressable both work well for this purpose, but if you need to add specific interaction areas or gestures, you might want to wrap only those areas that shouldn’t dismiss the keyboard.
2. If you have multiple text inputs and want each to dismiss when another is focused, you can also manage the `onFocus` and `onBlur` states in each input to handle keyboard dismissals or auto-focusing behaviors.

Using these methods shared by hire tech firms, you’ll create an intuitive experience for users by allowing them to tap outside of a `TextInput` to close the keyboard.