How to hide the keyboard on touch outside in react native

This tutorial will show you how to hide the keyboard on iOS and Android devices once the user clicks on any other view outside.

We will create one example project to test our implementation. I will keep this simple with one TextInput in a View. If you tap on the TextInput, it will open the keyboard and if you tap outside that TextInput, it will hide that keyboard.

React native app :

I am creating one basic react native with the below screen :

import React from 'react';
import {View} from 'react-native';
import {TextInput} from 'react-native-gesture-handler';

export default function HomeScreen() {
  return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      <TextInput
        style={{
          borderColor: 'gray',
          borderWidth: 1,
          width: '80%',
          height: '5%',
        }}
      />
    </View>
  );
}

One TextInput inside a View. It looks as like below on an iOS simulator :

React native keyboard

Hide the keyboard on tap outside :

Keyboard handling is easy in React Native. It provides one module called Keyboard for keyboard related stuff. Just import that module and call it’s dismiss method to hide a keyboard. In our case, we will wrap the full view with a TouchableWithoutFeedback and call this method on press :

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

export default function HomeScreen() {
  return (
    <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      <TextInput
        style={{
          borderColor: 'gray',
          borderWidth: 1,
          width: '80%',
          height: '5%',
        }}
      />
    </View>
    </TouchableWithoutFeedback>
  );
}

Now, if the keyboard is open and if you tap on outside, it will hide the keyboard.

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊❤️❤️