react-global-key-down-hook
v0.2.1
Published
React Hook to window keydown
Downloads
10
Maintainers
Readme
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
)