Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@rooks/use-key

imbhargav572kMIT4.11.2TypeScript support: included

Keyboard key handler hook for react

use, react-hooks.org, react, rooks, hooks, keyboard event, key

readme

@rooks/use-key

Note: Future updates to this package have moved to the main package rooks. All hooks now reside in a single package which you can install using

npm install rooks

or

yarn add rooks

Rooks is completely treeshakeable and if you use only 1 of the 50+ hooks in the package, only that hook will be bundled with your code. Your bundle will only contain the hooks that you need. Cheers!

TitleCard

Build Status

About

keypress, keyup and keydown event handlers as hooks for react.

Installation

npm install --save @rooks/use-key

Importing the hook

import useKey from "@rooks/use-key";

Usage

Basic example with keydown

function Demo() {
  const inputRef = useRef();
  function windowEnter(e) {
    console.log("[Demo 1] Enter key was pressed on window");
  }
  function vowelsEntered(e) {
    console.log("[Demo 1] You typed a vowel");
  }
  function capitalVowelsEntered(e) {
    console.log("[Demo 1] You typed a capital vowel");
  }
  // window is the target
  useKey(["Enter"], windowEnter);
  useKey(["a", "e", "i", "o", "u"], vowelsEntered, {
    target: inputRef
  });
  useKey(["A", "E", "I", "O", "U"], capitalVowelsEntered, {
    target: inputRef
  });
  return (
    <>
      <p>Press enter anywhere to trigger a console.log statement</p>
      <p>Press a,e,i,o,u in the input to trigger a console.log statement</p>
      <p>Press A,E,I,O,U in the input to trigger a different log statement</p>
      <input ref={inputRef} />
    </>
  );
}

render(<Demo />);

Multiple kinds of events

function Demo() {
  const inputRef = useRef();
  function onKeyInteraction(e) {
    console.log("[Demo 2]Enter key", e.type);
  }

  useKey(["Enter"], onKeyInteraction, {
    target: inputRef,
    eventTypes: ["keypress", "keydown", "keyup"]
  });
  return (
    <>
      <p>Try "Enter" Keypress keydown and keyup </p>
      <p>
        It will log 3 events on this input. Since you can listen to multiple
        types of events on a keyboard key.
      </p>
      <input ref={inputRef} />
    </>
  );
}
render(<Demo />);

Conditionally setting handlers

function Demo() {
  const inputRef = useRef();
  const [shouldListen, setShouldListen] = useState(false);
  function toggleShouldListen() {
    setShouldListen(!shouldListen);
  }
  function onKeyInteraction(e) {
    console.log("[Demo 3] Enter key", e.type);
  }

  useKey(["Enter"], onKeyInteraction, {
    target: inputRef,
    eventTypes: ["keypress", "keydown", "keyup"],
    when: shouldListen
  });
  return (
    <>
      <p>
        Enter key events will only be logged when the listening state is true.
        Click on the button to toggle between listening and not listening
        states.{" "}
      </p>
      <p>
        Handy for adding and removing event handlers only when certain
        conditions are met.
      </p>
      <input ref={inputRef} />
      <br />
      <button onClick={toggleShouldListen}>
        <b>{shouldListen ? "Listening" : "Not listening"}</b> - Toggle{" "}
      </button>
    </>
  );
}
render(<Demo />);

changelog

v3.6.0-canary.0 (2019-12-25)

:rocket: New Feature

  • fullscreen, storybook

:house: Internal

  • boundingclientrect-ref, countdown, docusaurus, fork-ref, geolocation, intersection-observer-ref, isomorphic-effect, mutation-observer-ref, outside-click-ref
  • Other

:memo: Documentation

v3.5.1 (2019-12-18)

:memo: Documentation

:house: Internal

3.4.3

  • Added new useCountdown hook

3.4.2

  • Fix types for useOutsideClickRef hook
  • Internal bug fixes

v3.4.0

  • New useBoundingclientrectRef hook
  • New useForkRef hook
  • New useOutsideClickRef hook
  • New useIsomorphicEffect hook
  • New useMutationObserverRef hook
  • New useIntersectionObserverRef hook
  • Minor bug fixes

v3.3.0

  • New useGeolocation hook
  • New useThrottle hook
  • Minor bug fixes

v3.2.2

  • Fix a minor bug in useKeys

v3.2.0

  • New hooks added

    • useOnWindowResize
    • useOnWindowScroll
    • useKeys
  • Allow localStorage and sessionStorage to store all kinds of values.

v3.1

  • New hook added useDebounce

v3

  • Critical bug with useKey with refs not detected was fixed
  • useWindowSize now returns innerHeight, innerWidth, outerHeight and outerWidth. It no longer returns height and width which were ambiguous.
  • useWorker has a new signature.
  • useInterval had issues with useState which have been resolved
  • usePrevious has a much simpler implementation using useRef
  • typescript types have been added to all the hooks
  • Storybook website has been added
  • Uniform major package version for all packages. It makes development easier and it also helps tracking compatibility.

v2

  • useToggle v2.0.0 Return value is now an array with two values instead of an object

Older

  • useInterval

    -1.1.1 (2019-01-20)

  • useOutsideClick

    • Fix SSR bug introduced
    • Also look for touch listeners now
  • rooks