Reputation: 3797
I have the following component
<ul id='list-view' style={this.props.style} onKeyDown={this.__matchEvent}>
{listItems}
{status}
</ul>
But the onKeyDown event is not firing at all, am i doing something wrong?
Upvotes: 1
Views: 2495
Reputation: 96
To follow up on Liubomyr Mykhalchenko:
Another way of adding focus capabilities to an html element that receives no focus by default (ul, li, div, ...) is to add a tabIndex
attribute.
There are 2 ways of using this:
By adding a specific number greater than 0 you can change the order of tabbing of elements on the page.
This is discouraged though, it can have great impact on accessibility.
This makes gives an element (that previously could not be focused) the possibility to be focusable. So your ul element would be able to receive focus.
However you should be aware that keyboard users might want to interact with this "dumb" element so you will need to add keyboard listeners and actions to this element (and even focus/hover states).
You are now entering the wonderful world of a11y :-)
Upvotes: 1
Reputation: 22933
For the onKeyDown
event to fire, your element has to either be focused, or contain an element that has focus when a key is pressed. If you switch <ul>
to <textarea>
you'll see that the key down event fires.
Unfortunately, there's no way to focus an <ul>
element. Your best option is to attach a key down listener on the document to catch all key down events, and see what the target was (which will only be an element that can have focus, or will be body
).
Upvotes: 2
Reputation: 268
To complete @anders-ekdahl answer.
You may use contentEditable
property to make some tags fire keyboard events
<div contentEditable
onKeyDown={this.handleKeyDown}>blablabla</div>
Upvotes: 1