react-global-key-down-hook
TypeScript icon, indicating that this package has built-in type declarations

0.2.1 • Public • Published

react-global-key-down-hook

A simple package to bind keys on components.


Setup

yarn add react-global-key-down-hook

OR

npm install --save react-global-key-down-hook


Example

import React, { useState } from 'react'
import useGlobalKeyDown from 'react-global-key-down-hook'
 
const App = () => {
  const [hidden, setHidden] = useState(false)
 
  useGlobalKeyDown(() => {
    setHidden(true)
  }, ['Esc', 'Escape'])
 
  return <div>{hidden && <div> Press ESC to hide</div>}</div>
}
 
export default App

or just using one key:

import React, { useState } from 'react'
import useGlobalKeyDown from 'react-global-key-down-hook'
 
const App = () => {
  const [hidden, setHidden] = useState(false)
 
  useGlobalKeyDown(() => {
    setHidden(true)
  }, 'Enter')
 
  return <div>{hidden && <div> Press Enter to hide</div>}</div>
}
 
export default App

you also can use it to control movement:

useGlobalKeyDown(() => setPositionY(positionY + 1), ['ArrowUp', 'w', 'k'])
useGlobalKeyDown(() => setPositionY(positionY - 1), ['ArrowDown', 's', 'j'])

It's possible to bind all keys, but it's just recommended to debug:

useGlobalKeyDown(
  (pressedKey) => console.log('Pressed key:', `"${pressedKey}"`),
  '_all'
)

Params

  useGlobalKeyDown(
    callBack: (pressedKey: string) => any,
    key: string | string[],
    disabled?: boolean
  )

Package Sidebar

Install

npm i react-global-key-down-hook

Weekly Downloads

0

Version

0.2.1

License

MIT

Unpacked Size

5.58 kB

Total Files

8

Last publish

Collaborators

  • jonmaciel