GlobalHotKeys(react-hotkeys) not working when focused on the input field

4.2k Views Asked by At

I am using React-hotkeys for the keyboard shortcuts on a React project. GlobalHotKeys not working when focused on the input field. Please help me, I am unable to find out what I am missing.

Demo (Recorded Screen Link): https://recordit.co/ffVKvn9uVw

<GlobalHotKeys keyMap={REGISTRATION_KEY_MAP} handlers={this.handlers}>
      <RegistrationForm
         ref={regFormRef}
         onBillClick={this.onBillClick}
         patientId={this.state.patientID}
         openBill={this.state.openBill}
     />
</GlobalHotKeys>

    const handlers = {
        REGISTER: () => console.log(regFormRef),
        REGISTER_AND_BILL:  () => console.log(regFormRef),
    };

  const REGISTRATION_KEY_MAP = {
    REGISTER: ['command+enter', 'ctrl+enter'],
    REGISTER_AND_BILL: ['enter'],
  };

Expected behavior

If I am using then it should directly fire the related action, the focus should not matter. Eg. I want to submit a form but currently, document focused on any input box then it should submit the form

Platform:

  • Version of react-hotkeys: react-hotkeys v2.0.0
  • Browser chrome
  • OS: iOS v10.13.6
3

There are 3 best solutions below

1
GAJESH PANIGRAHI On
configure({
    ignoreTags: ['input', 'select', 'textarea'],
    ignoreEventsCondition: function() {}
});

Will solve this issue.

0
Muhammed Rahif On

There is a way to enable hotkeys in input (also textarea and select), by passing a second parameter.

It's a 'options' parameter. To know more about parameters.

import { useHotkeys } from "react-hotkeys-hook";

function App() {
  useHotkeys("n", e => {
      e.preventDefault();
      e.stopPropagation();
      // Do your thing here
    },
    // Add your hotkeys options in here
    { enableOnTags: ["TEXTAREA", "INPUT"] } // To enable on ['TEXTAREA', 'INPUT']
  );

  return <div id="shortcuts">{children}</div>;
}

export default App;

0
imgss On

you can use the enableOnFormTags config


function ExampleComponent() {
  useHotkeys('meta+s', (e) => {
    e.preventDefault()

    alert('We saved your progress!')
    // ... set up our own saving dialog.
  }, {
    enableOnFormTags: ['input', 'select', 'textarea']
  })

  return (
    <div>
      <p>Press cmd+s (or ctrl+s for non mac) to open custom save dialog.</p>
    </div>
  )
}

see https://react-hotkeys-hook.vercel.app/docs/documentation/useHotkeys/disable-hotkeys#enable-hotkeys-on-form-fields