Skip to content

victorRicardo1/react-shortcut

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-shortcut

A small React + TypeScript utility to handle keyboard shortcuts in a simple and reusable way.

It provides:

  • A useShortcut hook to handle keyboard shortcuts on any element
  • A Shortcut component to wrap elements and enable shortcuts easily

Requirements

  • Node.js 18+
  • React 18 or 19 in the consuming project

Installing and Building the Library

This package is not published to npm. You can build and install it locally.


1) Install dependencies

Inside the react-shortcut folder:

npm install

2) (Optional) Build the library

If you have a build script configured (for example with tsc):

npm run build

If you are using the TypeScript source directly, this step may not be necessary.

3) Create an installable package

You can generate a .tgz package using:

npm pack

This will generate a file like:

react-shortcut-1.0.0.tgz

4) Install it in another project

Inside your react project:

npm install /path/to/react-shortcut/react-shortcut-1.0.0.tgz

Or install directly from the folder:

npm install /path/to/react-shortcut

Usage

Using the useShortcut Hook

Attach the returned callback to any focusable element's onKeyDown:

import React, { useCallback } from "react";
import { useShortcut } from "react-shortcut";

function MyComponent() {
  const onKey = useCallback((key: string, event: KeyboardEvent) => {
    alert(`Handled key: ${key}`);
  }, []);

  const onKeyDown = useShortcut("x", onKey);

  return (
    <button onKeyDown={onKeyDown}>
      Press "x" while this button is focused
    </button>
  );
}

You can also pass multiple keys:

useShortcut(["a", "b", "c"], onKey);

Using the Shortcut component

The Shortcut component wraps any element and injects the onKeyDown handler automatically:

import React, { useCallback } from "react";
import { Shortcut } from "react-shortcut";

function MyComponent() {
  const onKey = useCallback((key: string, event: KeyboardEvent) => {
    alert(`Handled key: ${key}`);
  }, []);

  return (
    <Shortcut keys="x" onKey={onKey}>
      <button>
        Press "x" while this button is focused
      </button>
    </Shortcut>
  );
}

Case sensitivity

Shortcuts are case-sensitive:

  • "a" is different from "A"

  • This follows the behavior of event.key from the browse

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors