0.0.1 • Published 3 years ago

@odnh/use-keypress v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

useKeyPress

Returns the key value when the key is pressed.

Install

yarn add @odnh/use-keypress
# or 
npm install @odnh/use-keypress

Use

  useKeyPress(selector?: Selector, target?: Target) => Selector[];

parameters

NameTypedefaultValuedescription
selectorEventKeycodekey event property selector(recommend code and key) detail
targetHTMLElement or React.MutableRefObjectbodyevent target element
type EventKey = 'code' | 'keyCode' | 'key' | 'which';

returns

EventKey[]

Example

import React from 'react';
import {useKeyPress} from '@odnh/use-keypress';

const SENTENCE_LIST = ['hi', 'bye'];

const App = () => {
  const [sentenceIndex, setSentenceIndex] = React.useState(0);
  const pressingCodes = useKeyPress();
  const nextSentence = React.useCallback(() => {
    setSentenceIndex(prev => prev+1);
  }, []);
  React.useEffect(() => {
    if(
      pressingCodes.includes('ControlLeft') &&
      pressingCodes.includes('KeyZ') {
        setSentenceIndex(prev => (
          prev > 0 ? prev-1 : prev;
        ));
      }
    )
  }, [pressingCodes])

  return (
    <>
      <p>{SENTENCE_LIST[sentenceIndex]}</p>
      <button onClick={nextSentence}>next</button>
    </>
  )
}