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.

2

There are 2 best solutions below

1
On

Can you try doing this?

<ReactCrop
    style={{maxWidth: "50%"}}
    crop={crop}
    onChange={setCrop}
>
    <img
       src={srcImage}
       onLoad={onLoad}
    />
</ReactCrop>
0
On

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