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

118
Visualizações
How can I show an image in the website of a react application, right after a user uploads it?

Here's the scenario: a user must upload a file, once he does it, I would want to display it on the page as soon as the server receives it. I tried conditional rendering but that does not work.

What should I do to make it work? Thanks in advance.

code:

import React, { useState } from 'react'

import './App.css'

function App() {
  const [image, setImage] = useState('')

  const submitHandle = (e) => {
    if (!image) {
      console.log('please upload an image')
    } else {
      console.log(e.target)

      e.preventDefault()
      console.log('submitted')
    }
  }

  return (
    <section>
      <div>
        <div>
          <h1>heading one</h1>
          <form onSubmit={submitHandle}>
            <input
              value={image}
              onChange={(e) => setImage(e.target.value)}
              type='file'
              accept='image/gif, image/jpeg, image/png'
            />
            <button type='submit'>submit</button>
          </form>
          {image && <img src={image} alt='image' />}
        </div>
      </div>
    </section>
  )
}

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

0

For an input of type file, its value cannot be set by code.

And to view the image immediately, you'll have to convert it into a string using a FileReader;

So we have to create another function loadImage and pass in the selected file as it's argument


Full Code

function App() {
  const [image, setImage] = useState('');
  
  const loadImage = (file) => {
    const reader = new FileReader();
    reader.addEventListener('load', e => setImage(e.target.result));
    reader.readAsDataURL(file);
  }

  const submitHandle = (e) => {
    if (!image) {
      console.log('please upload an image')
    } else {
      console.log(e.target)

      e.preventDefault()
      console.log('submiited')
    }
  }

  return (
    <section>
      <div>
        <div>
          <h1>heading one</h1>
          <form onSubmit={submitHandle}>
            <input
              onChange={(e) => loadImage(e.target.files[0])}
              type='file'
              accept='image/gif, image/jpeg, image/png'
            />
            <button type='submit'>submit</button>
          </form>
          {image && <img src={image} alt='image' />}
        </div>
      </div>
    </section>
  )
}
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