React hook and react component for subscribe to hotkeys
Support React Context API.
import{HotKey,Keys,KeySelector}from"@simprl/react-hot-keys";// with typescript:// const customSelector: KeySelector = (e) => e.key === 'Delete';constcustomSelector=(e)=>e.key==='Delete';constComponent=({onExit, onEvent})=>{return<><HotKeyselector={Keys.ESC}onKey={onExit}/><HotKeyselector={customSelector}onKey={onEvent}/><div>component with hot keys</div></>}import{useHotKey,Keys,KeySelector}from"@simprl/react-hot-keys";// with typescript:// const customSelector: KeySelector = (e) => e.key === 'Delete';constcustomSelector=(e)=>e.key==='Delete';constComponent=({onExit, onEvent})=>{useHotKey(Keys.ESC,onExit);useHotKey(customSelector,onEvent);return<div>component with hot keys</div>}import{HotKey,HotKeysContainer,Keys}from"@simprl/react-hot-keys";
...
<HotKeysContainer><HotKeyselector={Keys.ESC}onKey={()=>setV((state)=>state+1)}/>
....
<HotKeysContainer>
inner hot key container
<HotKeyselector={Keys.ESC}onKey={()=>setV((state)=>state+1)}/></HotKeysContainer>
....
</HotKeysContainer>By default HotKeysContainer is a div element with style = { width: 100%; height: 100%; }
You can set your own styles:
<HotKeysContainerclassName="myClassName">
...
</HotKeysContainer>- HotKeysContainer render a div and subscribe to keyboard events. Also it make React Context.
- HotKeysContainer receive event only if it or children DOM elements has focus.
- If keyboard event happen then check all HotKey components and useHotKey hooks inside react context.
- If selector return true then onKey handler call.
- If none handler call and property propagate is true, then process parent HotKeysContainer.