Closing keyboard in React Native and keeping the TextInput focused


(Roc Khalil) #1

I was facing an issue with Android’s keyboard always popping up when I select a TextInput. I’m using a hidden TextInput in my app to allow Pickers scan a product’s barcode with their barcode reader. However, they were annoyed by the keyboard showing after each scan.

In order to close the keyboard, I did some research on Android’s keyboard extension and RN Native modules.

Here’s how to implement it:

We should create a Native Module that calls InputMethodManager to close the keyboard when visible and add an onFocus function on our TextInput that calls the Native’s keyboard dismissal function.

Here’s how to do it:

  1. Create a Keyboard Native Module
    KeyboardModule.java
package com.xxx.xxx;

import android.app.Activity;
import android.view.inputmethod.InputMethodManager;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;

public class KeyboardModule extends ReactContextBaseJavaModule {

    public KeyboardModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "KeyboardFunctionalities";
    }

    @ReactMethod
    public void hideKeyboard() {
        final Activity activity = getCurrentActivity();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide
    }
}

KeyboardPackage.java

package com.xxx.xxx;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class KeyboardPackage implements ReactPackage {

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(
            ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();

        modules.add(new KeyboardModule(reactContext));

        return modules;
    }

}
  1. Register it in MainApplication.java
@Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            ...,
            new KeyboardPackage()
      );
    }
  1. Use it in your React Native code:
import { TextInput, NativeModules } from "react-native"

render(){
  return(
    <TextInput onFocus={() => NativeModules.KeyboardFunctionalities.hideKeyboard() } />
  )
}