mirror of
https://github.com/streamich/react-use.git
synced 2025-12-08 18:02:14 +00:00
More DRY code. Also move non-hooks to separate directories. BREAKING CHANGE: all `create*` factories been moved to `factory` subdirectory and in case direct import should be imported like `react-use/esm/factory/createBreakpoint` BREAKING CHANGE: `comps` directory renamed to `component`
47 lines
726 B
Markdown
47 lines
726 B
Markdown
# `useKey`
|
|
|
|
React UI sensor hook that executes a `handler` when a keyboard key is used.
|
|
|
|
## Usage
|
|
|
|
```jsx
|
|
import {useKey} from 'react-use';
|
|
|
|
const Demo = () => {
|
|
const [count, set] = useState(0);
|
|
const increment = () => set(count => ++count);
|
|
useKey('ArrowUp', increment);
|
|
|
|
return (
|
|
<div>
|
|
Press arrow up: {count}
|
|
</div>
|
|
);
|
|
};
|
|
```
|
|
|
|
Or as render-prop:
|
|
|
|
```jsx
|
|
import UseKey from 'react-use/lib/component/UseKey';
|
|
|
|
<UseKey filter='a' fn={() => alert('"a" key pressed!')} />
|
|
```
|
|
|
|
|
|
## Reference
|
|
|
|
```js
|
|
useKey(filter, handler, options?, deps?)
|
|
```
|
|
|
|
|
|
## Examples
|
|
|
|
```js
|
|
useKey('a', () => alert('"a" pressed'));
|
|
|
|
const predicate = (event) => event.key === 'a'
|
|
useKey(predicate, handler, {event: 'keyup'});
|
|
```
|