Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
How to display the selected image in reactjs

I wanted to upload images and display the image which was chosen, How to display the image after choosing. this is my code, help me display the image, I made the function to post the image, I can post multiple images in one click but i can't display the image to preview before upload , i try to use file reader but cannot display and upload.

   
  const [pImg, setPImg] = useState([]);
  const [images, setImages] = useState([]);

 
  const addImg = (ImagesPostDto) => {
    const data2 = new FormData();
    [...ImagesPostDto].forEach((Images) => {
      data2.append("ImagesPostDto", Images);
    });
    Axios.post(`/shop/${shopID}/Product/${pID}/Images`, data2)
      .then((res) => {
        if (res.status === 200) {
          setMessage({
            data: `${res.data.MESSAGE}`,
            type: "alert-success",
          });
          onShowAlert();
        }
      })
      .catch((err) => {
        setMessage({
          data: `${err.response.data.MESSAGE}`,
          type: "alert-danger",
        });
        setLoading(false);
        onShowAlert();
      });
  };

  const handleImageChange = (e) => {
    e.preventDefault();
    const ProductImg = e.target.files;
    setPImg(ProductImg);
const reader = new FileReader();

reader.onloadend = () => {
  setPImg(ProductImg);
  setImages(reader.result);
};
reader.readAsDataURL(ProductImg);
  };

  const handleProductSubmit = (event) => {
    event.preventDefault();
    addImg(pImg);
  };
  
  return (
    <div>
      
   
        <Form>
          <p>
            <Label htmlFor="file">Upload images</Label>
            <input
              type="file"
              id="file"
              onChange={handleImageChange}
              accept="image/png, image/jpg, image/jpeg"
              multiple
            />
          </p>
        </Form>
        <div className="">
          {/* {images.length > 0 ? (
            <div>
              {images.map((image) => (
                <p>
                  <img src={images} alt="" />
                </p>
              ))}
            </div>
          ) : null} */}
        </div>
      

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

If you want to render images then, create ObjectURL from files array and set the images State then it should work fine. I have commented the code related to API call so that we can focus on rendering the selected images.You can just simply copy this code and paste it in CodeSandBox it should work fine Here is your code a bit modified:

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [pImg, setPImg] = useState([]);
  const [images, setImages] = useState([]);

  // const addImg = (ImagesPostDto) => {
  //   const data2 = new FormData();
  //   [...ImagesPostDto].forEach((Images) => {
  //     data2.append("ImagesPostDto", Images);
  //   });
  //   Axios.post(`/shop/${shopID}/Product/${pID}/Images`, data2)
  //     .then((res) => {
  //       if (res.status === 200) {
  //         setMessage({
  //           data: `${res.data.MESSAGE}`,
  //           type: "alert-success"
  //         });
  //         onShowAlert();
  //       }
  //     })
  //     .catch((err) => {
  //       setMessage({
  //         data: `${err.response.data.MESSAGE}`,
  //         type: "alert-danger"
  //       });
  //       setLoading(false);
  //       onShowAlert();
  //     });
  // };

  const handleImageChange = (e) => {
    e.preventDefault();
    console.log("event", e);
    const ProductImg = [...e.target.files];
    const images = ProductImg.map((image) => URL.createObjectURL(image));
    console.log("images", images);
    setImages(images);
  };

  // const handleProductSubmit = (event) => {
  //   event.preventDefault();
  //   addImg(pImg);
  // };

  return (
    <div>
      <form>
        <p>
          <label htmlFor="file">Upload images</label>
          <input
            type="file"
            id="file"
            onChange={handleImageChange}
            accept="image/png, image/jpg, image/jpeg"
            multiple
          />
        </p>
      </form>
      <div className="">
        {images.length > 0 && (
          <div>
            {images.map((image, index) => (
              <p key={index}>
                <img src={image} alt="" />
              </p>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

about 4 years ago · Santiago Gelvez Report

0

You need to fetch the Images from GET API and set the response in setImages than it will show right now the images variable is empty array.

about 4 years ago · Santiago Gelvez Report

0

As far I can understand your requirement, you need to preview the Images Either when you have selected or After uploaded.

What you can do is, whenever you are preparing the FormData or at the time of change event, you can store each selected file's ObjectURL in another state and Easily can display these images via the State.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!