react-mousetrap-hook
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

react-mousetrap-hook

A simple wrapper on top of mousetrap to work with react.

It returns proxy ref object to bind the action to multiple inputs

This package is using lbundle as bundler ✨

Installation

NPM registry

# npm
npm i react-mousetrap-hook mousetrap

# yarn
yarn add react-mousetrap-hook mousetrap

# pnpm
pnpm i react-mousetrap-hook mousetrap

# bun
bun i react-mousetrap-hook mousetrap

JSR registry

# deno
deno add @mrii/react-mousetrap-hook

# jsr
npx jsr add @mrii/react-mousetrap-hook

Usage

bind events for specific components

import { useCallback } from 'react';
import { useMousetrap } from '@mrii/react-mousetrap-hook';

export const Component: React.FC = () => {
  // returns proxyRef from `@mrii/react-proxy-ref`
  const proxyRef = useMousetrap(
    ['enter', 'shift+enter'],
    useCallback(({ combo }) => {
      console.log(combo);

      // submit
    }, [])
  );

  return (
    <>
      {/* the names doesn't matter, we are looping over them */}
      <input ref={proxyRef.email} name='email' />
      <input ref={proxyRef.password} name='password' />
    </>
  );
};

bind events to the document

import { useCallback } from 'react';
import { useDocumentMousetrap } from '@mrii/react-mousetrap-hook';

export const Component: React.FC = () => {
  // returns proxyRef from `@mrii/react-proxy-ref`
  useDocumentMousetrap(
    'ctrl+k',
    useCallback(() => {
      // open search
    }, []),
    'keyup'
  );

  //...
};

API

useMousetrap

hook to initiate Mousetrap on set of elements

Property Type Default Description Version
arg0:keys string | string[] undefined keys to be applied to Mousetrap.bind(keys) 1.0.0
arg1:cb Function undefined callback to be applied to Mousetrap.bind(, cb) 1.0.0
arg2:action string? undefined optional action to be applied to Mousetrap.bind(, , action) 1.0.0

return: ProxyRefObject<keyof any, TRef>


useDocumentMousetrap

hook to initiate Mousetrap to the document

Property Type Default Description Version
arg0:keys string | string[] undefined keys to be applied to Mousetrap.bind(keys) 1.0.0
arg1:cb Function undefined callback to be applied to Mousetrap.bind(, cb) 1.0.0
arg2:action string? undefined optional action to be applied to Mousetrap.bind(, , action) 1.0.0

return: void


Notes

  • it's important to use useCallback when passing the callback to the hook, so you will save a lot of performance.
  • there is no need to memoize the keys, because we are shallow comparing the changes.

Package Sidebar

Install

npm i react-mousetrap-hook

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

25.5 kB

Total Files

26

Last publish

Collaborators

  • abd-ulhameed-maree