Course contentsShow
← React Native
Lesson 225 of 1,5553. Core Primitive ComponentsFree lesson

Managing External Keyboard Shortcuts

Learners will map keyboard events to actions in the application interface.

In this lesson, you will learn how to trigger specific application actions when a user presses keys on a physical keyboard connected to their device.

Why use keyboard shortcuts?

When users connect a physical keyboard to their tablet or phone, they expect to navigate the interface without touching the screen. By mapping specific key combinations to your app’s functions, you create a professional, "desktop-class" feel that improves accessibility and efficiency.

Using the KeyboardAvoidingView or Keyboard API? Not quite.

While React Native provides APIs for managing the on-screen software keyboard, physical hardware keys are managed differently. We use the KeyboardKey or the keyCommands prop (often via the Pressable component or specific native-interop wrappers) to listen for unique input sequences like Cmd + S or Enter.

Implementing a basic shortcut

To map a keyboard event to an action, you define a command that specifies the input (the key) and, optionally, modifierFlags (like holding down Command or Control).

Here is how you might map the "Enter" key to a "Submit" function:

import { Pressable, Text } from 'react-native';

const SubmitButton = ({ onPress }) => {
  return (
    <Pressable
      // This tells the system: when 'Enter' is pressed, trigger onPress
      keyCommands={[{ input: '\r', actionKey: 'submit' }]}
      onKeyDown={(e) => {
        if (e.key === 'Enter') onPress();
      }}
      onPress={onPress}
    >
      <Text>Submit Form</Text>
    </Pressable>
  );
};

The Concept in Action

Think of this as creating a "shortcut bridge." Normally, a user clicks your button with their finger. By adding a key command, you are essentially telling the React Native runtime: "If the user presses this specific sequence on their physical hardware, pretend as if they tapped this button."

It is important to keep these shortcuts intuitive. Use standard combinations (like Esc to close a modal or Enter to confirm a selection) to ensure your app behaves exactly how your users expect it to when they move from their laptop to their mobile device.

Key Takeaway: Managing external keyboard shortcuts allows you to bridge physical hardware inputs to your app's existing logic, ensuring a seamless experience for power users who prefer keyboards over touch input.