bamya
bamya

Reputation: 416

Determine Which Key is Pressed on React Native Without Using Input Field

With the opportunity of Silicon chips on Mac. We started to develop a Mac application by using React Native. We are not using any input field, but we need to identify which key is pressed from keyboard while the user is focussed to our App. Basically we want to listen all keyboard events while user is using our App. What is the best approach for this problem?

Upvotes: 0

Views: 392

Answers (1)

justcodin
justcodin

Reputation: 1013

If you use react-native on macOS, then you may probably use react-native-web with electron or directly in the web browser.

This is my solution :

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

export default class App extends Component {
    handleKeyDown = (e) => {
        console.log(`${e.code}`);
        // Do your stuff...
    };

    componentDidMount = () => {
        document.onkeydown = this.handleKeyDown;
    };

    componentWillUnmount = () => {
        document.onkeydown = null;
    };

    render = () => {
        return (
            <View>
                <Text>{'Example'}</Text>
            </View>
        );
    };
}

Upvotes: 1

Related Questions