概要
React-Bootstrapにはファイルのアップロードを行うForm.File
の要素があるのですが、デフォルトのままだと下記の画像のようなシンプルなインプットのレイアウトになります。
これを独自のインプットの表示にするやり方を、今回紹介します。
どのようにしたいのか
下記のTwitterのイメージにあるような、アップロードした画像をクリックするとファイルのダイアログが表示されるように、今回実装してみます。
対応方法
こちらのドキュメントにある通り、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>
);