≪ Today I learned. RSS購読
公開日
タグ
JavaScript, React
著者
ダーシノ(@bc_rikko)

Reactでautofocus属性が使えないときの対処法

dialogを表示するときにどこにフォーカスを当てるかを指定するためにautofocus属性を使う。ただ、ReactではautoFocus: booleanというインターフェースを持ちながら、なぜか属性が削除されてしまうというバグ?仕様?がある。

環境

対処法

autofocus="true"と指定することでautofocus属性が削除されなくなる。

<dialog>
  ...
  <button>セカンダリ</button>
  <button autofocus="true">プライマリ</button>
</dialog>

Issueやブログを読んでみるとref.current.focus()をすればいいという情報も多いが、そもそも全主要ブラウザがサポートしている機能に対してハックが必要なのはナンセンスだと感じる。

動作しないパターン

<button autoFocus>xxx</button>
<button autoFocus="true1">xxx</button>
// `autoFocus={true}`が本来の使い方のはず
<button autoFocus={true}>xxx</button>

<button autofocus>xxx</button>
<button autofocus={true}>xxx</button>

参考