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.
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>
));