Home > Back-end >  How to display the selected image in reactjs
How to display the selected image in reactjs

Time:07-18

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>
      

CodePudding user response:

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>
  );
}

CodePudding user response:

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.

  • Related