https://www.npmjs.com/package/key-layers-react

Click here to share this article on LinkedIn »

While creating react apps I often face with key listeners problem. One of the most popular it is disabling all “esc” key listeners when the app opens any dialog and enabling only its “esc” key listener.

Simple dialog example

For applications with rich shortcut keys list and when dialog can open child dialog, this issue becomes more urgent. For this situation, it will be good to have the solution that resolves this problem automatically.

Z-index for key listeners

On my opinion the best way to resolve this problem it is to introduce layers for the key listeners.

When the key listener is added, in options, it is possible to specify a z-index of the layer or a flag that indicate necessary to create a new layer with the biggest z-index. What is more, the key listeners are enabled only for the layer with the biggest z-index.

High Order Component (HOC)

According to good practice was decided to implement a High Order Component (HOC). HOC adds two methods into the child component.

addKeyListene - add new key listener to the layer.

removeKeyListene - remove the key listener from the layer.

Using these methods listeners can be easily added.

In the example above is defined new component that connected to the layer with zIndex = 4. Method addKeyListene allows to add a new key down event listener and this listener will be enabled only when layer with zIndex = 4 is the layer with the biggest zIndex. Current example shows how to add a listener for any key. But in most cases, it is necessary to handle specific keys events or keys combinations. For example, if needs to handle only “F” and “K” it’s easy to do.

In the previews examples all event listeners was added to the layer with zIndex = 4. But in some cases such as modal components needs to disable all event listeners and enable only listeners of the modal component. Such behavior is possible with the help of high-level layer auto-creating. Just use HOC without zIndex.

Listeners auto deleting.

When component unmounting all event listeners removing automatically. So no necessary to remove listeners on componentWillUnmount lifecycle method. As for auto-created layers, they will delete automatically as well as listeners.

Summary

High Order Component “react-key-layers” provides comfortable handling key events. If web application contains the several abstract layers such as file browsing, image preview, video preview etc. If active layer needs to handle own events and lock event handlers of the other layers, react-key-layers can help to resolve this task.

Simple demo