Home > Mobile >  Multiple images have uploaded but not showing in UI (React Js)
Multiple images have uploaded but not showing in UI (React Js)

Time:10-06

I'm trying to upload images using react js but I'm not able to upload multiple images at the same time even though I gave input as multiple.

<input type="file" title="" className={styles.inputFile} multiple={true} onChange={handleChange} />

 const [formData, setFormData] = useState({
    orgId: "6114285831310bfd5b09c28178e",
    orgWallpaper: [],
  }); 

const handleChange = (e) => {
    if (e.target.files && e.target.files[0]) {
      setFormData((form) => ({
        ...form,
        orgWallpaper: [...form.orgWallpaper, URL.createObjectURL(e.target.files[0])],
      }));
    }
  };

{formData?.orgWallpaper?.map((item, key) => (
                  {console.log(item, "mapitem")}
                  <img className={styles.wallpapers   " "   styles.active} src={item} alt="" />

CodePudding user response:

You should change handleChange like below

const {useState} = React;

const MultipleFilesUpload = () => {
  const [formData, setFormData] = useState({
    orgId: "6114285831310bfd5b09c28178e",
    orgWallpaper: [],
  });

  const handleChange = (e) => {
    var files = e.target.files;
   for (let i = 0; i <files.length; i  ) {
   setFormData((form) => ({
        ...form,
        orgWallpaper: [...form.orgWallpaper, URL.createObjectURL(files[i])]})
        )}};
        
  return ( 
  <div>
      <input type="file" title="" multiple onChange={handleChange}/> 
      <div class="gallery">
      {
      formData.orgWallpaper.map((item, key) =>
        <img width ="48px" src ={item} alt= "" />
      )} 
      </div> 
   </div>
)};

ReactDOM.render( <MultipleFilesUpload/> ,
  document.getElementById("root")
);
.gallery {
  display: flex;
}

.gallery img {
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

CodePudding user response:

You may check this :

...(e.target.files?.map(file=>URL.createObjectURL(file))??[])

and also remove console log, its actually breaking the return syntax. If you want to check console.log then also write a return :

 {formData?.orgWallpaper?.map((item, key) => ( <img key={key} className={styles.wallpapers   " "   styles.active} src={item} alt="" />)
    }
  • Related