react-keydown
raw JSON → 1.9.12 verified Fri May 01 auth: no javascript
A higher-order component and decorator for React that binds keyboard events to components and methods. Current stable version is 1.9.12. It uses a declarative syntax to define key bindings, supports modifier keys, scopes events to active components, and adds only a single document listener regardless of the number of bindings. Released as CommonJS, with a separate UMD branch. Compared to alternatives like react-hotkeys, it is lighter (2KB gzipped) and simpler, with direct method decoration but less flexibility in key combinations and sequencing.
Common errors
error Module not found: Can't resolve 'react-keydown' ↓
cause Package not installed or missing from dependencies.
fix
Run 'npm install --save react-keydown'
error The decorator is not a function ↓
cause Decorator plugin not enabled or Babel misconfigured.
fix
Install @babel/plugin-proposal-decorators and add to .babelrc: { 'plugins': ['@babel/plugin-proposal-decorators', { 'legacy': true }] }
Warnings
deprecated react-keydown may not be actively maintained; check for future updates. ↓
fix Consider using react-hotkeys or react-use-gesture as alternatives.
gotcha Decorator syntax requires Babel with decorator transform plugin (e.g., @babel/plugin-proposal-decorators). ↓
fix Install and configure the decorator plugin, or use the HOC pattern: keydown('enter')(MyComponent).
gotcha Only one keydown listener attached to document; scoping relies on component focus/active state, which may not work in all UI scenarios. ↓
fix Ensure components are properly focused or clicked to receive events; consider using event.stopPropagation if needed.
Install
npm install react-keydown yarn add react-keydown pnpm add react-keydown Imports
- default wrong
const keydown = require('react-keydown')correctimport keydown from 'react-keydown' - Keys wrong
import Keys from 'react-keydown'correctimport { Keys } from 'react-keydown' - keydownScoped
import { keydownScoped } from 'react-keydown'
Quickstart
import React from 'react';
import keydown, { Keys } from 'react-keydown';
class MyComponent extends React.Component {
state = { count: 0 };
@keydown('enter')
increment() {
this.setState(prev => ({ count: prev.count + 1 }));
}
render() {
return (
<div>
<p>Press Enter to increment: {this.state.count}</p>
</div>
);
}
}
export default MyComponent;