Skip to content

useKeyPress

Edit on GitHub
@volvo-cars/react-utils v1.3.0

Runs a callback when matching keys are pressed on the document. Use it for global keyboard shortcuts like closing overlays with Escape or moving between items with arrow keys.

import { useState } from 'react';
import { useKeyPress } from '@volvo-cars/react-utils';
function SearchDialog() {
const [open, setOpen] = useState(true);
useKeyPress('Escape', () => {
setOpen(false);
});
if (!open) {
return null;
}
return (
<div role="dialog" aria-modal="true">
<p>Press Escape to close.</p>
</div>
);
}

Pass an array to listen for several keys with one hook. The callback receives the KeyboardEvent.key value that triggered the match:

import { useState } from 'react';
import { useKeyPress } from '@volvo-cars/react-utils';
function Stepper() {
const [step, setStep] = useState(0);
useKeyPress(['ArrowLeft', 'ArrowRight'], (key) => {
setStep((current) => {
if (key === 'ArrowRight') {
return current + 1;
}
return Math.max(0, current - 1);
});
});
return <p>Current step: {step}</p>;
}

useKeyPress(keysToListenTo, callback) accepts:

  • keysToListenTo — a key name or array of key names, e.g. 'Escape' or ['ArrowLeft', 'ArrowRight']
  • callback — called with the pressed KeyboardEvent.key value

The hook does not return a value.

  • Matching is case-insensitive
  • The callback runs once for each matching key press
  • The listener fires before the event reaches the focused element, including when focus is inside <input> or <textarea>. If your shortcut uses text-editing keys (arrows, Space, etc.) and you don’t want it firing while users type, check event.target or scope the listener to a specific container element yourself.