Scope hotkeys to non-focusable elements
mainTo scope hotkeys to container elements like <div>, <section>, or <span>, you must make them focusable. Add a tabIndex={-1} attribute to the element. This allows the element to receive focus via JavaScript or mouse clicks (enabling the scoped hotkey) without adding the element to the natural keyboard tab order of the page.
function ScopedHotkey() {
const [count, setCount] = useState(0)
const ref = useHotkeys('shift+a', () => setCount(prevCount => prevCount + 1))
return (
<div ref={ref} tabIndex={-1} style={{border: '2px solid #9e768f', padding: '12px'}}>
<p>The count is {count}. Click inside this area to enable the hotkey.</p>
</div>
)
}