-
Notifications
You must be signed in to change notification settings - Fork 119
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[BUG] Attaching resulting ref to a different element stops the shortcuts/hotkeys from working #1116
Comments
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. |
It sure does not. I already have working code including a test failing without my changes. |
Here's the PullRequest: #1117 |
Thank you for work, I'll have a look into it! |
I have a simpler implementation here: #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 <textarea /> 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.
The text was updated successfully, but these errors were encountered: