1

I want to add crop image functionality to my project. So for that, I am using the react-image-crop npm package. I read the documentation and write code but still, I am getting an error. When I select an image from my pc then it should appear on localhost:3000 but the Image is not shown on localhost:3000. When I configure it then I found an error that onLoadedImage does not set the image URL which is null in the beginning. That's why It does not show the image. Kindly help me that how can I get the image url on onLoadedImage as I tried a lot but did not find any solution. Here is my code.

import "./App.css";
import {Form, Button, Container} from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import {useState} from "react";
// import "react-image-crop/dist/ReactCrop.css";
import ReactCrop from "react-image-crop";
import 'react-image-crop/dist/ReactCrop.css';
function App() {
  const [srcImg, setSrcImg] = useState(null);
  const [image, setImage] = useState(null);
  const [crop, setCrop] = useState({aspect: 16 / 9});
  const [result, setResult] = useState(null);

  const handleImage = async (event) => {
    setSrcImg(URL.createObjectURL(event.target.files[0]));
    console.log(event.target.files[0]);
  };

  const getCroppedImg = async () => {
    try {
      console.log("image")
      console.log(image)
      const canvas = document.createElement("canvas");
      const scaleX = image.naturalWidth / image.width;
      const scaleY = image.naturalHeight / image.height;
      canvas.width = crop.width;
      canvas.height = crop.height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(
        image,
        crop.x * scaleX,
        crop.y * scaleY,
        crop.width * scaleX,
        crop.height * scaleY,
        0,
        0,
        crop.width,
        crop.height
      );

      const base64Image = canvas.toDataURL("image/jpeg", 1);
      setResult(base64Image);
      console.log(result);
    } catch (e) {
      console.log(e)
      console.log("crop the image");
    }
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    console.log(result);
  };
 
  // const onLoad = (img)=>{
  //   console.log("on load function")
  //   console.log(img)
  //   setImage(img)
  // }
  return (
    <Container className="container" fluid="md">
      <h5 className="header">React Image Crop</h5>
      <Form onSubmit={handleSubmit}>
        <Form.Group className="mb-3" controlId="formBasicEmail">
          <Form.Label>Select Image you want to crop</Form.Label>
          <div>
            <input type="file" accept="image/*" onChange={handleImage} />
          </div>
          <div>
            {srcImg && (
              <div>
                <ReactCrop
                  style={{maxWidth: "50%"}}
                  src={srcImg}
                  onImageLoaded={setImage}
                  crop={crop}
                  onChange={setCrop}
                />
                <Button className="cropButton" onClick={getCroppedImg}>
                  crop
                </Button>
              </div>
            )}
            {result && (
              <div>
                <img src={result} alt="cropped image" />
              </div>
            )}
          </div>
        </Form.Group>
        <Button variant="primary" type="submit">
          Submit
        </Button>
      </Form>
    </Container>
  );
}

export default App;

When I run my project the following screen apears on localhost:3000 enter image description here

when I choose an image from my pc it does not appear on localhost:3000. It must appear on screen for crop. Please help me to solve this issue.

Abdul Sammad
  • 127
  • 1
  • 8
  • I stumbled on this issue today. `onLoadedImage` is probably no longer used – Hiroki Oct 30 '22 at 06:06
  • I think this post might help you out. [React image crop preview not rendering](https://stackoverflow.com/questions/72656236/reactcrop-preview-not-rendering/72669427#72669427). – Cyborg Apr 28 '23 at 06:52

2 Answers2

0

use onComplete={setImage} instead of onImageLoaded(setImage)

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
minhaj
  • 1
  • 1
-1

Can you try doing this?

<ReactCrop
    style={{maxWidth: "50%"}}
    crop={crop}
    onChange={setCrop}
>
    <img
       src={srcImage}
       onLoad={onLoad}
    />
</ReactCrop>
  • While This May Answer The Question & Solve It Too, But It Would Not Benefit Future Readers Who Encounter This. Please Consider Adding An Explanation To The Answer To Make It More Easy To Understand. Please Also Read: [How Do I Write A Good Answer?](https://stackoverflow.com/help/how-to-answer) – Albert Logic Einstein Aug 19 '22 at 01:32