Leticia Fatima
Leticia Fatima

Reputation: 522

state is empty when defining an image

I'm creating an image upload, but when I select the image and put the image properties in a state, the state is empty.

code:

export default function UploadImage() {
  const [image, setImage] = React.useState(null);

  function imageSelectedHandle(event) {
    setImage(event.target.files[0]);
  }

  return (
    <>
      <AdvertiserPhoto for="image">
        <div>
          <img src={!me ? noPhoto : verifyPhoto(me.profile_image)} alt="" />
          <IconCam color="white" width="40" height="30" />
        </div>
      </AdvertiserPhoto>
      <input
        type="file"
        id="image"
        name="image"
        style={{ display: "none" }}
        accept="image/jpg"
        onChange={imageSelectedHandle}
      />
    </>
  );
}

Upvotes: 1

Views: 503

Answers (1)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

You first need to read the image file to show

Here is a working demo with some changes since I don't have code for other components

https://codesandbox.io/s/modest-glitter-b48w3?file=/src/App.js:129-348

function imageSelectedHandle(event) {
    const [file] = event.target.files;
    var reader = new FileReader();
    reader.readAsDataURL(file);

   reader.onloadend = function (e) {
    setImage(reader.result)
   }
}

Or

function imageSelectedHandle(event) {
    const [file] = event.target.files;
    setImage(URL.createObjectURL(file));
}

Upvotes: 2

Related Questions