skip to Main Content

I want to upload images in a list using input file and display it.

My code displays the 1st upload but after the 2nd upload it doesn’t display.

function DisImg() {

    const [file, setFile] = useState([]);

    function handleChange(e) {
        let sel = URL.createObjectURL(e.target.files[0]);
        setFile(prevV => [
            ...prevV, sel
        ]);
    }

    return (
        <>
            <Input type="file" onChange={handleChange}>Choose file</Input>
            {
                file.map(() => {
                    return <img src={file} alt="documents" height="50px" width="50px" />
                })
            }
        </>
    );
}

2

Answers


  1. You’re not using the values stored in the file array. You pass file directly to the src of the image.

    .map provides you with the current value when you’re mapping over the file array.

    {file.map((src) => {
      return <img src={src} alt="documents" height="50px" width="50px" />;
    })}
    
    Login or Signup to reply.
  2. add source variable like url, also add index variable as a unique key that will help to track.

    <Input type="file" onChange={handleChange}>Choose file</Input>
                {file.map((url,index) => {
                        return <img src={url} key={index} alt="documents" height="50px" width="50px" />
                    })
                }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search