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?

More than 3 years have passed since last update.

React-BootstrapのForm.File要素の表示をカスタマイズする

Posted at

概要

React-Bootstrapにはファイルのアップロードを行うForm.Fileの要素があるのですが、デフォルトのままだと下記の画像のようなシンプルなインプットのレイアウトになります。
スクリーンショット 2021-03-21 4.34.03.png
これを独自のインプットの表示にするやり方を、今回紹介します。

どのようにしたいのか

下記のTwitterのイメージにあるような、アップロードした画像をクリックするとファイルのダイアログが表示されるように、今回実装してみます。
スクリーンショットスクリーンショット 2021-03-20 16.43.04.png

対応方法

こちらのドキュメントにある通り、Form.Fileにcustomを設定します。その上で、FormFile.Input要素を配置して、これを画像の表示箇所に被るようにCSSで位置を調整します。画像が変わったときに走る関数は、FormFile.Input側に設定します。

実装サンプル

画像が未設定の時は、FontAwesomeIconの人アイコンを表示します。

sample.js
const [displayIconSrc, setDisplayIconSrc] = useState(undefined);

function onChangeIconImage(e) {
  if (e.target.files.length > 0) {
    setValue("iconImage", e.target.files);
    const imageFile = e.target.files[0];
    // FileReaderオブジェクトを使ってファイル読み込み
    var reader = new FileReader();
    // ファイル読み込みに成功したときの処理
    reader.onload = function () {
      setDisplayIconSrc(reader.result);
    };
    // ファイル読み込みを実行
    reader.readAsDataURL(imageFile);
  } else {
    setDisplayIconSrc(undefined);
  }
}

return(
  <Form.File id="iconImage" name="iconImage" type="file" custom>
    <FormFile.Input
      style={{ width: "70px", height: "70px" }}
      onChange={onChangeIconImage}
    />
    <div>
      {displayIconSrc ? (
        <img
          src={displayIconSrc}
          className="mt-2 mr-2 rounded-circle"
          style={{
            width: "70px",
            height: "70px",
            position: "relative",
            bottom: "75px",
          }}
        />
      ) : (
        <FontAwesomeIcon
          icon={faUser}
          className="fa-2x mt-2 mr-2"
          style={{
            width: "70px",
            height: "70px",
            position: "relative",
            bottom: "75px",
          }}
        />
      )}
    </div>
    <div
      style={{
        position: "relative",
        bottom: "50px",
        left: "170px",
      }}
    >
      アイコン画像を選択してください
    </div>
 </Form.File>
);

以下のような表示になります。画像をクリックするとファイル選択のダイアログが表示されます。
スクリーンショット 2021-03-21 4.44.43.png

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?