react-hotkeys-hook
react-hotkeys-hook copied to clipboard
Focus on text field but enters hotkey
The following example:
REPRO CODE:
function ExampleComponent() {
useHotkeys('/', () => inputRef.current.focus());
const inputRef = useRef();
return (
<input type="text" ref={inputRef} placeholder="search via '/'" />
)
}
EXPECTED BEHAVIOUR:
- without a focus in the field, typing
/
would focus in the field so that a search string could be entered
ACTUAL BEHAVIOUR:
- without focus in the field, typing '/' puts focus in the field and sets its initial value to
/
I could not determine from the documentation if there is an option to suppress propagating the initial entry of the hotkey?
Related ask: Is there a documented example for having a hotkey such as "/" be used to focus to an input field, but also allow "/" to be entered once the field has focus? That is, if the field does not have input and I type "/abc" then the search field gets focus and the text value becomes "abc". But if the field has focus and I type "abc/def" then the field gets the value "abc/def".
I got a working example of what I think is valid behaviour. But it is more code that I'd expect to have to do. Wondering if either:
- I'm missing some capability of react-hotkeys-hook I should be aware of?
- This example is a potential "new feature" for react-hotkeys-hook ?
function ExampleComponent() {
const HOTKEY = '/';
const inputRef = useRef();
const [enableHotkey, setEnableHotkey] = useState(true);
const handleHotkeyInput = () => {
inputRef.current.focus();
setEnableHotkey(false);
}
const handleInputChange = () => {
if (!enableHotkey) {
if (inputRef.current.value === HOTKEY) {
inputRef.current.value = "";
}
}
};
const handleInputBlur = () => {
setEnableHotkey(true);
}
useHotkeys(HOTKEY, handleHotkeyInput, {enableHotkey});
console.log("is hotkey enabled?", enableHotkey);
return (
<>
<input type="text" ref={inputRef} onChange={handleInputChange} onBlur={handleInputBlur} />
<br />
<button onClick={() => console.log("inputRef value", inputRef.current.value)}>output to console</button>
</>
)
}
But even this doesn't work perfectly. For example: 0. With no focus on the input field
- type "/abc"
- press the output to console button
- type "/def"
EXPECTED:
- input field has the value "abcdef"
ACTUAL:
- input field has the value "abc/def"
I'll look into it, thanks for raising the issue