1.0.0 • Published 15 days ago

react-mousetrap-hook v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
15 days ago

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

PropertyTypeDefaultDescriptionVersion
arg0:keysstring \| string[]undefinedkeys to be applied to Mousetrap.bind(keys)1.0.0
arg1:cbFunctionundefinedcallback to be applied to Mousetrap.bind(, cb)1.0.0
arg2:actionstring?undefinedoptional action to be applied to Mousetrap.bind(, , action)1.0.0

return: ProxyRefObject<keyof any, TRef>


useDocumentMousetrap

hook to initiate Mousetrap to the document

PropertyTypeDefaultDescriptionVersion
arg0:keysstring \| string[]undefinedkeys to be applied to Mousetrap.bind(keys)1.0.0
arg1:cbFunctionundefinedcallback to be applied to Mousetrap.bind(, cb)1.0.0
arg2:actionstring?undefinedoptional 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.