0.0.8 • Published 3 years ago

@odnh/use-key-press v0.0.8

Weekly downloads
6
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<S = string, T = HTMLBodyElement>(selector?: Selector<T>, target?: Target<T>) => S[];

parameters

NameTypedefaultValuedescription
selectorSelector(event) => event.codeselect value of event
targetHTMLElement or React.MutableRefObjectbodyevent target element
type Selector<S = string> = (event: KeyboardEvent) => S;

return

list of values contained by selector

Example

demo

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);
  }, [setSentenceIndex]);
  React.useEffect(() => {
    if(
      pressingCodes.includes('ControlLeft') &&
      pressingCodes.includes('KeyZ') {
        setSentenceIndex(prev => (
          prev > 0 ? prev-1 : prev;
        ));
      }
    )
  }, [pressingCodes, setSentenceIndex])

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

3 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.5

3 years ago

0.0.4

3 years ago

0.0.1

3 years ago