Tarlen
Tarlen

Reputation: 3797

onKeyDown not firing on component

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

Answers (3)

Donaldini
Donaldini

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:


tabIndex="n" (n is a positive number)

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.


tabIndex="0"

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

Anders Ekdahl
Anders Ekdahl

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

Liubomyr Mykhalchenko
Liubomyr Mykhalchenko

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

Related Questions