JAOdev
JAOdev

Reputation: 331

Load image into img via input event

The reason for the query is because I am having trouble displaying the image that is loaded in the tag:

With the input event, the handleChange function is executed, in it it is confirmed that the event is the one corresponding to photo number 1, hence the if (fieldName == "photo1"). But the image is never displayed. Indeed in photo1, I get the name of the image and its shape.

How is it possible to show the image? o What am I doing wrong?

const SetItem = () =>{

    const [foto1,setFoto1]=useState<string>("-");

    const handleChange = (fieldName: string) => (e:any) => {
        if(fieldName=="foto1"){
            setFoto1(e.currentTarget.files[0].name);
            let img=document.getElementById("imagen1");
            (img! as HTMLImageElement).src=foto1!;
        }
     };

    return(
      <input id="inputFile1" type="file" accept="image/*" onChange={ handleChange("foto1")} />
      <img id="imagen1" src={foto1} alt="your image" />
    );
}

Upvotes: 1

Views: 539

Answers (2)

nmanikiran
nmanikiran

Reputation: 3148

For img tag we need an image path (relative/absolute), not the file name.

Else we can read the file with browser FileReader API and display the image in data uri format.

can you check the exmaple below

import React, { useState } from "react";
export default function App() {
  const [image, setImage] = useState("");

  const handleChange = (file) => {
    const input = file.currentTarget;

    var reader = new FileReader();
    reader.onload = function () {
      const dataURL = reader.result;
      setImage({ name: input.files[0].name, src: dataURL });
    };
    reader.readAsDataURL(input.files[0]);
  };
  return (
    <div className="App">
      <input
        id="inputFile1"
        type="file"
        accept="image/*"
        onChange={handleChange}
      />
      <img id="imagen1" src={image.src} alt="your" />
    </div>
  );
}

Upvotes: 2

timbersaw
timbersaw

Reputation: 660

Try converting your image to base64 string with this function and then set src to that base64 string

 const fileToBase64 = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
  
  

Upvotes: 1

Related Questions