Reputation: 220
I have an app (react/redux) which is split in to two parts:
I'd like to have a key listener for the Grid that listens to key presses.
E.g. pressing down should select the next GridArea(Element), and pressing Escape should select the "parent", if applicable.
In the GridEditor, you can edit properties on the various GridAreaElements etc. via e.g. input fields. When interacting with the GridEditor, and especially these input fields, I don't want the key press listener to be enabled, as it can e.g. deselect the element that is being edited.
So what I'd like is to enable the key listener when the Grid component (and its children) is focused/active, but disable it when the Grid is blurred/inactive, i.e. the GridEditor is focused/active.
Are there any suggestions on how to do this?
Upvotes: 2
Views: 2030
Reputation: 220
I figured it out. Not sure if it's the best solution though.
First of all, to make an event listener fire on events on a DOM element, e.g. a div
, the element it is attached to must have focus. We can make sure an element is focusable by giving it a tabIndex
:
<div className="myDiv" tabIndex="0" ref="myDiv" >
By also adding a ref
to the div, we can access the DOM element and attach a keydown event listener to it in componentDidMount
:
this.refs.myDiv.addEventListener('keydown', this.props.handleKeyPress, false)
This keydown listener will only be triggered when the DOM element it is attached to is focused :)
Upvotes: 3