Skip to content
  • Sponsor
  • Notifications You must be signed in to change notification settings
  • Fork 3.2k

Files

Latest commit

d3d5bc9 Β· Jul 17, 2019

History

History
36 lines (25 loc) Β· 707 Bytes

useKeyPress.md

File metadata and controls

36 lines (25 loc) Β· 707 Bytes

useKeyPress

React UI sensor hook that detects when the user is pressing a specific key on their keyboard.

Usage

import {useKeyPress} from 'react-use';

const keys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];

const Demo = () => {
  const states = [];
  for (const key of keys) states.push(useKeyPress(key)[0]);

  return (
    <div style={{textAlign: 'center'}}>
      Try pressing numbers
      <br />
      {states.reduce((s, pressed, index) => s + (pressed ? (s ? ' + ' : '') + keys[index] : ''), '')}
    </div>
  );
};

Examples

const isPressed = useKeyPress('a');

const predicate = (event) => event.key === 'a';
const isPressed = useKeyPress(predicate);