How to Hide Keyboard in React Native TextInput

The on-screen keyboard plays a vital role in mobile applications when it comes to user input. However, there are times when you might want to hide the keyboard programmatically, for example, after a form submission.

In this blog post, we will cover various methods for hiding the keyboard in React Native using the TextInput component.

Prerequisites

  • A functional React Native environment
  • Basic understanding of React Native and JavaScript

Set Up a Basic TextInput

Firstly, let’s create a simple TextInput component to understand how the keyboard appears and behaves.

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

const App = () => {
  return (
    <View>
      <TextInput placeholder="Tap to show keyboard" />
    </View>
  );
};

Use Keyboard.dismiss()

React Native’s Keyboard API provides a dismiss method that hides the keyboard.

First, import the Keyboard API.

import { Keyboard } from 'react-native';

Then, use Keyboard.dismiss() to hide the keyboard.

const hideKeyboard = () => {
  Keyboard.dismiss();
};

The Keyboard.dismiss() is a function that hides the on-screen keyboard.

Trigger Keyboard Dismissal

You might want to hide the keyboard after certain actions. Here are some examples.

On Button Press

import { Button } from 'react-native';

<Button
  title="Hide Keyboard"
  onPress={() => Keyboard.dismiss()}
/>

After Form Submission

const handleSubmit = () => {
  // Your form submission logic here
  Keyboard.dismiss();
};

Using blurOnSubmit and onSubmitEditing

The TextInput component has two props that can be used for this purpose: blurOnSubmit and onSubmitEditing.

<TextInput
  placeholder="Tap to show keyboard"
  blurOnSubmit={true}
  onSubmitEditing={() => Keyboard.dismiss()}
/>

Explanation

  • blurOnSubmit automatically blurs (loses focus) the input field when the submit button is pressed.
  • onSubmitEditing is an event that gets triggered when the submit button is pressed.

Hiding the keyboard in a React Native application can be achieved using various methods like the Keyboard API or specific TextInput props. Understanding when and how to hide the keyboard can lead to a much more user-friendly application.

Similar Posts

Leave a Reply