1
    const [photo, setPhoto] = React.useState([]);

    const addPhoto = async (e) => {
      await setPhoto(e.target.files);
    };

    const returnPhoto = () => {
        if (photo.length > 0) {
         for (let i = 0; i < photo.length; i++)  {
             return(
                <div style={{background: '#303030', display: 'inline-flex'}}>
                    <img alt='pic' style={{maxHeight: '10em', maxWidth: '10em'}} src={URL.createObjectURL(photo[i])}/>
                </div>
             )}}}

Does anyone see what I did wrong? I'm trying to return a useState's current selected files... I assume I should alter the addPhoto() function but so far I don't know how.

thomas305
  • 82
  • 7

1 Answers1

2

Your main problem is that putting return in a regular for loop exits the loop on the first iteration. You'd want to use something like map() to return an array of JSX elements.

Because the files property is a FileList, you won't be able to directly use map() but you can convert it to an array.

You could also optimise this by memo-ising the created URLs

const [ photos, setPhotos ] = useState([]); // really think this should be plural

const addPhoto = (e) => { // no need for async
  setPhotos(e.target.files);
};

// photos is a FileList so convert to an array
const photoUrls = useMemo(() =>
  Array.from(photos, URL.createObjectURL), [ photos ]);

useEffect(() => () => {
  // cleanup
  photoUrls.forEach(URL.revokeObjectURL);
}, [ photoUrls ]);

const returnPhoto = () => photoUrls.map(url => (
  <div style={{background: "#303030", display: "inline-flex"}}>
    <img
      src={url}
      alt="pic"
      style={{maxHeight: "10em", maxWidth: "10em"}}
    />
  </div>
));
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Wow, great answer... first i've seen on here involving useMemo() and everything on google says i needed to install bootstrap – thomas305 Feb 24 '22 at 03:58
  • 1
    I totally forgot that `input.files` is a `FileList` and not an array so sorry about leading you up the garden path earlier – Phil Feb 24 '22 at 03:59