Lucas Bernardo
Lucas Bernardo

Reputation: 549

How do I listen to keyboard input in React Native

I have a Honeywell Scanner that outputs text when scanning bar codes. I can use it as a "keyboard" for text inputs, which comes in very handy because I don't have to interface anything. But it has the downside of having to focus an input and thus displaying the virtual keyboard of the mobile device, which is unacceptable for the project I'm working on.

Is there any way to get the value scanned without having to focus an input? I believe that listening for the keyPress events or the likes of it would be the way to go, storing the value inputted in a variable elsewhere than the textInput.

If there's a better way of achieving this, I'm all ears!

Upvotes: 17

Views: 16361

Answers (2)

Lucas Bernardo
Lucas Bernardo

Reputation: 549

Okay everyone, found a way to do this without going way too crazy. It's not the most elegant solution, but it does exactly what I need and doesn't add too much to the code.

import { Keyboard, TextInput } from 'react-native';

...

<TextInput
  autoFocus
  onFocus={() => Keyboard.dismiss()} />

The name of the game here was autoFocus and onFocus={() => Keyboard.dismiss()} />.

Now I'll be using https://www.npmjs.com/package/react-native-keyevent as suggested by @MattAft to listen for key presses (unfortunately this package wont give me the actual scanner input. It will, however, trigger the keyDown event) to focus the TextInput when the scanner reads something.

UPDATE A coworker helped me a bit with this a few days ago when we had some time to refactor this component, and we found out there is a listener called onKeyMultipleListener on the react-native-keyevent package which not only listens for multiple simultaneous keyPresses but also captures the entire input, which is exactly what we needed here.

Upvotes: 8

Paul McLoughlin
Paul McLoughlin

Reputation: 2289

I know react-native has a keyboard module to control keyboard events

The Keyboard module allows you to listen for native events and react to them, as well as make changes to the keyboard, like dismissing it.

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

class Example extends Component {
  componentWillMount () {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
  }

  componentWillUnmount () {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  _keyboardDidShow () {
    alert('Keyboard Shown');
  }

  _keyboardDidHide () {
    alert('Keyboard Hidden');
  }

  render() {
    return (
      <TextInput
        onSubmitEditing={Keyboard.dismiss}
      />
    );
  }
}

Upvotes: 3

Related Questions