Closed vilemj-Viclick closed 1 month ago
Changing the return type does not change the behavior of the code. Typescript ist not present during runtime.
@JohannesKlauss I am sure he uses TS to describe the desired JS implementation as TS is a great tool for this.
Changing the return type does not change the behavior of the code. Typescript ist not present during runtime.
It sure does not. But by using a callback, your code can actually react (haha... 😄) to a change in the element to which the ref is attached to.
I already have working code including a test failing without my changes. I hope it will all make sense when presented with my suggestions.
Here's the PullRequest: #1117
Thank you for work, I'll have a look into it!
I have a simpler implementation here: https://github.com/JohannesKlauss/react-hotkeys-hook/pull/1132
Describe the bug
If you attach the result of the hook
useHotkeys
to a different element than it was initially attached to, it breaks.To Reproduce
Steps to reproduce the behavior:
const ref = useHotkeys(...);
in your component.<element1 ref={ref} />
<element2 ref={ref} />
I made a CodePen to illustrate this better.
Here's the gist of the demo:
It renders either or based on a button toggle. Supposedly a situation where you toggle between a multi-line and simple input situation. But it's purely an example.
When focus is inside any of the input tags (input or textarea) pressing Enter increments a counter. The value of the counter is rendered as well.
After you use the Toggle button (be it once or multiple times) the Enter key no longer increments the counter.
Expected behavior
When the ref is attached to a different instance the eventHandler should re-attach. => Call
addEventHandler
on the new instance. Of-course after clearing the old one. The old instance can stay in the DOM after all, though it does not in my example.Environment:
Additional context
How to fix:
To fix this, the returned Ref will need to be a
RefCallback<T>
instead ofMutableRefObject<T>
. By passing a RefCallback, your callback will be called by React every time the instance it's attached to changes.I can and may submit a Pull-Request with a fix.