7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】<input type='number'>にマウススクロールでの数値入力を無効にする

Last updated at Posted at 2023-02-04

サンプル

<input type= 'number' />

といった数値入力の入力フォームがあるとします。
画面上でこの入力フォームにフォーカスし、マウスをスクロールすると数値が入力されてしまう場合があります。

解決策

これを無効にするには、e.preventDefault();だけでは無効にできません。
.addEventListenerの第3引数でpassive: falseが必要になります。
passive: falseは、リスナー内で e.preventDefault() を呼ぶ可能性がある。という意味になります。
passive: true(デフォルト値)は、リスナー内で e.preventDefault() は呼ばない。という意味になります。(リスナーの実行を待たずデフォルト動作を実行します。* パフォーマンスの向上になる)
なので、<input>に、フォーカス時にこのpassiveをfalseにさせます。

<input 
  type= 'number' 
  onFocus={(e) =>
          e.target.addEventListener(
            'wheel',
            (e) => {
              e.preventDefault();
            },
            { passive: false }
          )
        }
/>

これで入力フォームがフォーカスされている時のマウススクロールが無効化され、数値が入力されません。
以上が解決方法でした。

参考にした記事

7
1
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
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?