setCropBoxData react-cropper not Working when initializing image

582 Views Asked by At

I have an orignal Image which I am passing as src of a cropper. Now I am trying to set the adjusted image width and height when the cropper modal is open but somehow it does not set the initial width and height of the already existing image. Can anyone tell me what wrong I am doing?

  <Cropper
      style={{ height: 390, width: '100%' }}
      aspectRatio={16 / 9}
      guides={false}
      src={"https://tappio-development.s3.eu-central-1.amazonaws.com/user/1648980920749-tour-2-3.jpg"}
      //   ref={(cropper) => {
      //     this.cropper = cropper;
      //   }}
      viewMode={1}
      dragMode="move"
      cropBoxMovable={false}
      zoomTo={zoom}
      responsive={true}
      onInitialized={(instance) => {
        const img = new Image();
        img.src = `https://tappio-development.s3.eu-central-1.amazonaws.com/user/1648980934596-tour-2-3.jpg`;

        img.onload = () => {
           //trying to load already width and height from already existing image
          instance.setCropBoxData({
            x: img.width,
            y: img.height,
            width: img.width,
            height: img.height,
          });
          //setting to use cropper instance
          setCropper(instance);
        };
      }}
    />
1

There are 1 best solutions below

0
On

I don't know if you've yet found a solution for this problem, but I struggled with it today, filed a bug report, and came up with something that worked ok for me.

const [cropper, setCropper] = useState()

useEffect(()=>{
    if(cropper) cropper.setCropBoxData(the_data_object)
}, [cropper])

return <Cropper
    onInitialized={instance => setCropper(instance)}
    ...src, etc
/>

I also tried useLayoutEffect and that did not work, so I think somewhere in react-cropper is a race condition or order of operations bugaboo with regard to rendering. Regardless, the cropBoxData prop seems broken.

Anyway, this worked for me and has unblocked my progress. I hope it helps you and anyone else!