Skip to main content

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

ArgumentDescriptionTypeDefaultValue
modifierkey modifierKeyModifier (Required)-
optionsoptional paramsUseModifierOptions | undefined-

UseModifierOptions

PropertyDescriptionTypeDefaultValue
eventsEvent names that will prompt update to modifier states(keyof WindowEventMap)[]['mousedown', 'mouseup', 'keydown', 'keyup']
initialInitial value of the returned refbooleanfalse

KeyModifier

export type KeyModifier = 'Alt' | 'AltGraph' | 'CapsLock' | 'Control' | 'Fn' | 'FnLock' | 'Meta' | 'NumLock' | 'ScrollLock' | 'Shift' | 'Symbol' | 'SymbolLock';