Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
Any reason why only the last clicked img file is returning?
    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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda