I have a component that uses react hooks to register hotkeys: useMousetrap.
That's a hooks-wrapper for the mousetrap library.
Here is the component:
const MyComponent = ({ name }) => {
const sayHi = () => {
alert(`Hello from Component ${name}`);
};
useMousetrap('x', sayHi);
return (
<div>
Component {name}
</div>
);
};
When I implement that component inside some other component or page, everything works fine. But now say I want to have two components on the same page:
<div>
<MyComponent name="A" />
<MyComponent name="B" />
</div>
Now both components try to register the hotkey. It seems like it's always the one that appears later in the document flow, that succeeds. So if I press x in the example above, the alert would say Hello from Component B.
Is there a way to make sure that only one component is ever active? I was thinking of registering and unregistering those hotkeys depending on which component is in view, but useMousetrap being a hook seems to make conditional logic quite difficult. I am bit confused here.
Is there a quick & easy way I can turn the hotkeys on/off conditionally?