1.0.1 • Published 3 years ago
@mrii/react-mousetrap-hook v1.0.1
@mrii/react-mousetrap-hook
A simple wrapper on top of mousetrap to work with react.
Installation
# yarn
yarn add @mrii/react-mousetrap-hook mousetrap
# npm
npm i @mrii/react-mousetrap-hook mousetrapUsage
bind events for specific components
import type React from 'react';
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(() => {
      // 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 type React from 'react';
import { useCallback } from 'react';
import { useMousetrap } from '@mrii/react-mousetrap-hook';
export const Component: React.FC = () => {
  // returns proxyRef from `@mrii/react-proxy-ref`
  useMousetrap(
    'ctrl+k',
    useCallback(() => {
      // open search
    }, []),
    'keyup'
  );
  //...
};Notes
- it's important to use 
useCallbackwhen 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.