21
9

More than 5 years have passed since last update.

React + Material UIでファイル送信ボタン

Last updated at Posted at 2019-01-31

フォームでファイル送信ボタン<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回当たるのが難点…)

参考
https://stackoverflow.com/questions/40589302/how-to-enable-file-upload-on-reacts-material-ui-simple-input

21
9
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
21
9