<aside> 🌿 前回に続いて、商品情報登録ページの ・商品画像の登録(画像アップロード)・プレビュー・削除 の実装を行う

</aside>

<aside> 🌿 今回使用するメソッドについてはこちら ドキュメント

Upload files with Cloud Storage on Web | Firebase Storage

</aside>

■目次

1. 画像用コンポーネントの作成

  1. componentsディレクトリにProductsディレクトリを作成する

    スクリーンショット 2022-10-06 15.27.21.png

  2. Productsディレクトリ内にImageArea.jsxを作成し、以下のように画像アップロード用コンポーネントを作成する

    スクリーンショット 2022-10-06 15.29.14.png

    ※ 今回はMUIのicon(Material Icons)を使って、画像アップロードができることを表現する

    Material Icons - Material UI

    ▼コード例

    /**
    * <input type="file" />で、クリックするとエクスプローラーやfinderが表示されて、
    * ファイルや画像がアップロードできるようになる
    * 今回はアイコンをクリックでfinderを表示させたいので、labelタグでラップしつつ、inputタグは
    * CSSで非表示にさせている(display: none;)
    */
    
    import { IconButton, styled } from "@mui/material";
    import React from "react";
    import AddPhotoAlternateIcon from "@mui/icons-material/AddPhotoAlternate";
    
    // フォーカス時の影の形を調整
    const CustomizedIconButton = styled(IconButton)`
      height: 48px;
      width: 48px;
    `;
    
    const ImageArea = (props) => {
      return (
        <div>
          <div className="u-text-right">
            <span>商品画像を登録する</span>
            <CustomizedIconButton>
              <label>
                <AddPhotoAlternateIcon />
                <input className="u-display-none" type="file" id="image" />
              </label>
            </CustomizedIconButton>
          </div>
        </div>
      );
    };
    
    export default ImageArea;
    
  3. ProductEdit.jsxを開き、ImageAreaコンポーネントを設置する

    npm start を実行し、意図した表示がされているか一旦確認する

    ▼コード例

    import React, { useCallback, useState } from "react";
    import { PrimaryButton, SelectBox, TextInput } from "../components/UIkit";
    import { useDispatch } from "react-redux";
    import { saveProduct } from "../reducks/products/operations";
    **import ImageArea from "../components/Products/ImageArea";**
    
    const ProductEdit = () => {
    	〜〜〜
    
      return (
        <section>
          <h2 className="u-text__headline u-text-center">商品の登録・編集</h2>
          <div className="c-section-container">
            **<ImageArea />**
    		〜〜〜
        </section>
      );
    };
    
    export default ProductEdit;
    

    ▼イメージ画像

    スクリーンショット 2022-10-06 16.10.39.png

2. 画像アップロード機能の作成

コード解説【前半】

https://www.youtube.com/watch?v=CDW_yryn1Rc&list=PLX8Rsrpnn3IWavNOj3n4Vypzwb3q1RXhr&index=15

https://www.youtube.com/watch?v=CDW_yryn1Rc&list=PLX8Rsrpnn3IWavNOj3n4Vypzwb3q1RXhr&index=15

ここまでがblob生成の話

次からはファイル名をランダムな文字列で生成する話