0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

div要素でKeyboardEventが発火しない理由と対策【React】

Posted at

問題のコード

以下のコードでは、onKeyDownイベントが発火しません。

qiita.rb
  const startAction = (e: any) => {
    if (e.key === 'Enter' || e.key === ' ') console.log('hello');
  };
  
  return (
    <div
      className='h-screen w-full flex items-center justify-center'
      onKeyDown={startAction}
    >
      スペースかEnterを押してね!
    </div>
  );

これではeventが起こりませんでした。

原因

以下の2点が原因です

  • KeyboardEventはフォーカスを持つ要素でのみ発火する
  • div 要素はフォーカスを持たない

Interactive elements must be focusable

If the user can interact with an element (for example, using touch or a pointing device),
then it should be focusable using the keyboard. You can make it focusable by adding a
tabindex=0 attribute value to it.
That will add the element to the list of elements that can be focused by pressing the Tab key,
in the sequence of such elements as defined in the HTML document.

解決法

divtabIndex属性を追加して、フォーカス可能にすることで解決できます。

HTMLの場合はtabindexですが、JSXの場合はtabIndexになります

それではtabIndexdivに追加します。以下は修正後のコードです

qiita.rb
  const startAction = (e: any) => {
    if (e.key === 'Enter' || e.key === ' ') console.log('hello');
  };
  return (
    <div
      tabIndex={0}
      className='h-screen w-full flex items-center justify-center'
      onKeyDown={startAction}
    >
      スペースかEnterを押してね!
    </div>
  );

結果↓

qiita.rb
hello
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?