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?

Chakra UI のModalのフォーカス管理

0
Posted at

発端

Chakra UI のModalで、autoFocus を falseにしているのに、モーダル内の要素が再レンダリングされたときに、最初のInput要素に自動的にフォーカスが当たってしまった。
※ Chakra UIは、v2系を使用。

試したこと

  • モーダル内の全てのInputタグに autoFocus が含まれないことを確認
  • モーダル内の全てのInputタグに明示的に autoFocus={false} を指定
    → 解消せず
  • Chakra UI のModalタグに autoFocus={false} を指定
    → 解消せず
  • Chakra UI のModalタグに trapFocus={false} を指定
    → モーダル内の最初のInput要素に自動的にフォーカスが当たらなくなったが、tabキーでモーダル外の要素に移動できてしまう

問題の解消方法

根本的な解決方法ではないですが、以下のように useEffect 関数を使って、
再レンダリング時に少し遅れて document.activeElement.blur() を呼び出すようにすることで、最初のInput要素に当たったフォーカスを外すことができます。

isLoading の部分には、再レンダリングのトリガーとなるフラグを設定すると良いです。

useEffect(() => {
    if (isOpen && !isLoading) {
      setTimeout(() => {
        if (document.activeElement instanceof HTMLElement) {
          document.activeElement.blur();
        }
      }, 100);
    }
  }, [isLoading]);
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?