1

I'm using the library "React Cropper" (https://www.npmjs.com/package/react-cropper).

I have this code (as many examples):

import React from 'react';
import Cropper from 'react-cropper';

export default class PublishPhoto extends React.Component {
constructor(props) {
    super(props);
    this.state = 
    {
        src: '',
        cropResult: null,
    };
    this.onChangeImage = this.onChangeImage.bind(this);
    this.cropImage = this.cropImage.bind(this);
}

onChangeImage(e)
{
    e.preventDefault();
    let files;
    if (e.dataTransfer) {
      files = e.dataTransfer.files;
    } else if (e.target) {
      files = e.target.files;
    }
    const reader = new FileReader();
    reader.onload = () => {
      this.setState({ src: reader.result });
    };
    reader.readAsDataURL(files[0]);
}

cropImage() 
{
    if (typeof this.cropper.getCroppedCanvas() === 'undefined') {
      return;
    }
    this.setState({
      cropResult: this.cropper.getCroppedCanvas().toDataURL(),
    });
}

render(){
  return(
        <div>
            <div>Seccion de publicar foto</div>

            <input type="file" id="uploadImage" name="uploadImage" onChange={this.onChangeImage} />

            <Cropper
                style={{ height: 400, width: '100%' }}
                //aspectRatio={16 / 9}
                preview=".img-preview"
                guides={false}
                src={this.state.src}
                 />

                <button onClick={this.cropImage} style={{ float: 'right' }}>
                    Cortar imagen
                </button>


        </div>

    );  
}
}

But when do click on "Cortar imagen" buttom the javascript console show me the error: Uncaught TypeError: Cannot read property 'getCroppedCanvas' of undefined.

I tried use "this.refs.cropper.getCroppedCanvas()" instead "this.cropper.getCroppedCanvas()" but the "this.refs" is a empty object.

Thanks :/

2 Answers2

0

Self-response.

Missing the reference in the compontent react; like:

<Cropper
style={{ height: 400, width: '100%' }}
preview=".img-preview"
guides={false}
src={this.state.src}
ref={cropper => { this.cropper = cropper; }}
/>
  • 1
    Hi. I am doing exactly the same but after image crop I am still getting null in cropResult. Any idea why the setState is not setting state? Thanks. – user321 Jun 29 '20 at 12:25
0

For my case, i was actually using functional component of Cropper and was assigning ref like so:

const cropperRef = useRef<ReactCropperElement>(null);

<Cropper
  ref={cropperRef}
  ...
/>

But that was not the issue. The issue was, i was dynamically importing react-cropper. I don't know why it caused the error but it chaging it to normal import fixed it.

Hope it helps someone.

Ali Baghban
  • 517
  • 1
  • 5
  • 13