title: React-native key board events
body: <p>I am writing a react native app and need to implement keyboard events inside components.</p>
  
  <p>I tried with following code and did not success.</p>
  
  <pre><code>import { DeviceEventEmitter } from 'react-native';
  
  export default class KeyEvent {
    static onKeyDownListener(cb) {
      KeyEvent.removeKeyDownListener();
      console.log('Key Down');
      this.listenerKeyDown = DeviceEventEmitter.addListener('onKeyDown', cb);
    }
  
    static removeKeyDownListener() {
      if (this.listenerKeyDown) {
        this.listenerKeyDown.remove();
      }
    }
  
    static onKeyUpListener(cb) {
      console.log('Key up');
      KeyEvent.removeKeyUpListener();
      this.listenerKeyUp = DeviceEventEmitter.addListener('onKeyUp', cb);
    }
  
    static removeKeyUpListener() {
      if (this.listenerKeyUp) {
        this.listenerKeyUp.remove();
      }
    }
  }
  </code></pre>
  
  <p>Call inside componentDidMount function relevant component as follows.</p>
  
  <pre><code>componentDidMount() {
      console.log('componentDidMount');
      // if you want to react to keyDown 
      KeyEvent.onKeyDownListener((keyCode) =&gt; {
        console.log(`Key code pressed: ${keyCode}`);
      });
  
      // if you want to react to keyUp 
      KeyEvent.onKeyUpListener((keyCode) =&gt; {
        console.log(`Key code pressed: ${keyCode}`);
      });
    }
  
    componentWillUnmount() {
        console.log('componentWillUnmount');
      // if you are listening to keyDown 
      KeyEvent.removeKeyDownListener();
  
       // if you are listening to keyUp 
      KeyEvent.removeKeyUpListener();
    }
  </code></pre>
  
  <p>Can anyone help me to fix this or suggest any other way of doing this. I need to press a button on enter key down.</p>