useKeyModifier
React Sensor Hook that tracks state of any of the supported modifiers - see Browser Compatibility notes
Usage
Live Editor
function Demo() { const Button = (props: { mode: boolean; name: string }) => { const { mode, name } = props; return ( <button style={mode ? { background: "var(--c-input-border-focus)" } : {}}> {name} </button> ); }; const capsLock = useKeyModifier("CapsLock"); const numLock = useKeyModifier("NumLock"); const scrollLock = useKeyModifier("ScrollLock"); const shift = useKeyModifier("Shift"); const control = useKeyModifier("Control"); const alt = useKeyModifier("Alt"); return ( <div> <div style={{ marginBottom: 10 }}> <Button mode={capsLock} name="CapsLock" /> <Button mode={numLock} name="NumLock" /> <Button mode={scrollLock} name="ScrollLock" /> </div> <div> <Button mode={shift} name="Shift" /> <Button mode={control} name="Control" /> <Button mode={alt} name="Alt" /> </div> </div> ); };
Result
Loading...
API
useKeyModifier
Returns
boolean
: Whether the key is pressed
Arguments
Argument | Description | Type | DefaultValue |
---|---|---|---|
modifier | key modifier | KeyModifier (Required) | - |
options | optional params | UseModifierOptions | undefined | - |
UseModifierOptions
Property | Description | Type | DefaultValue |
---|---|---|---|
events | Event names that will prompt update to modifier states | (keyof WindowEventMap)[] | ['mousedown', 'mouseup', 'keydown', 'keyup'] |
initial | Initial value of the returned ref | boolean | false |
KeyModifier
export type KeyModifier = 'Alt' | 'AltGraph' | 'CapsLock' | 'Control' | 'Fn' | 'FnLock' | 'Meta' | 'NumLock' | 'ScrollLock' | 'Shift' | 'Symbol' | 'SymbolLock';