フォームでファイル送信ボタン<input type="file" />
をMaterial UIの <Button>
で実装する方法。
実際、とても簡単でした。
<Button
component="label"
>
ファイル送信ボタンです
<input
type="file"
className="inputFileBtnHide"
/>
</Button>
input type="file"を見た目非表示にするCSSはこんな感じ
.inputFileBtnHide {
opacity:0;
appearance: none;
position: absolute;
}
考え方は以下の2点
-
<input type="file" />
はCSSで非表示にしておく -
<Button>
を<label>
で囲んで、for属性で繋ぐ
注意点は、 inputのidは必ず書くこと。
そして <label for="{input:file要素のID}">
に必ず書くこと
component="span"
でButtonはspanタグになりますが、ちゃんとTabキーでのフォーカスも当たりキーボード操作も対応されます。
(ただフォーカスがlabelとinput、2回当たるのが難点…)