javascriptandroidmobileexpo

How to integrate React Native KeyEvent with Expo?


I am looking for a way to get input data from device's hardware barcode scanner. I found a library that reportedly can get the job done, which is React Native KeyEvent.

However, the instructions mostly lead me to edit the gradle files inside android folder. Since I am using Expo, I do not have the android folder to follow the document.

Without Ejecting to ExpoKit, is there any other way to integrate them?


Solution

  • I managed to get the plugin working....but it was a challenge. Here are the steps (for some reason, I had to use 'yarn'. 'npm' didn't work):

     yarn add react-native-keyevent
     yarn add --dev react-native-keyevent-expo-config-plugin
    

    Add the following line to app.json file in the "expo" section:

     "plugins": ["react-native-keyevent-expo-config-plugin"],
    

    Edit your component to import the package:

     import KeyEvent from "react-native-keyevent";
    

    Set listeners:

     KeyEvent.onKeyDownListener((keyEvent) => {....}
    

    Don't forget to remove listeners when your component unmounts:

     KeyEvent.removeKeyDownListener();
    

    Now here's the tricky part - it won't work with Expo Go. You can still run your app in Expo Go, but your app won't pick up keystrokes on the external keyboard. So, to test it, you need to actually build your app and then install it on a device.

    Also, I only managed to get it working on Android. I don't need it to work on iOS, so didn't spend any time on it. Therefore, I'm not sure if it's possible to get it working on iOS.